/**
 * Copyright (c) 2010-2012 EBM WebSourcing, 2012-2015 Linagora
 * 
 * This program/library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or (at your
 * option) any later version.
 * 
 * This program/library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program/library; If not, see <http://www.gnu.org/licenses/>
 * for the GNU Lesser General Public License version 2.1.
 */
package org.ow2.petals.log.handler;

import static org.junit.Assert.assertTrue;
import static org.ow2.petals.commons.log.Level.MONIT;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ow2.petals.log.formatter.LogDataFormatter;

/**
 * 
 * @author Mathieu CARROLLE - EBM WebSourcing
 * 
 */
public class TestFileHandlerTest {

    private String LOG_RECORD_MESSAGE = "TestFileHandler test message ";

    private TestFileHandler handler;

    private static int count = 0;

    @Before
    public void createHandler() throws IOException {
        handler = new TestFileHandler("test_" + count++);
        handler.setFormatter(new LogDataFormatter());
    }

    @After
    public void afterTest() {
        if (handler != null) {
            handler.close();
        }
    }

    @Test
    public void testInfoHandlerWithInfoRecord() throws IOException {
        handler.setLevel(Level.INFO);
        publish(Level.INFO, 10);
        testLogEntries(handler.getLogEntries(), 10);
    }

    @Test
    public void testFinestHandlerWithMonitRecord() throws IOException {
        handler.setLevel(Level.FINEST);
        publish(MONIT, 10);
        assertTrue(handler.getLogEntries().size() == 10);
        testLogEntries(handler.getLogEntries(), 10);
    }

    @Test
    public void testInfoHandlerWithFinestRecord() throws IOException {
        handler.setLevel(Level.INFO);
        publish(Level.FINEST, 10);
        assertTrue(handler.getLogEntries().size() == 0);
    }
    
    private void testLogEntries(List<String> logEntries, int expectedEntry) {
        assertTrue(logEntries.size() == expectedEntry);
        for (int i = 0; i < 10; i++) {
            assertTrue(logEntries.get(i).endsWith(LOG_RECORD_MESSAGE + i));
        }
    }

    private void publish(Level level, int nb) {
        for (int i = 0; i < nb; i++) {
            handler.publish(new LogRecord(level, LOG_RECORD_MESSAGE + i));
        }
    }
}
