package org.xbib.logging.test.handlers;

import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

import org.xbib.logging.handlers.ConsoleHandler;
import org.xbib.logging.handlers.OutputStreamHandler;
import org.xbib.logging.test.AssertingErrorManager;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.handlers.ConsoleHandler.Target;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class OutputStreamHandlerTest {

    private StringWriter out;
    private OutputStreamHandler handler;

    private static final Formatter NO_FORMATTER = new Formatter() {
        public String format(final LogRecord record) {
            return record.getMessage();
        }
    };

    public OutputStreamHandlerTest() {
    }

    @BeforeEach
    public void prepareBuffer() {
        out = new StringWriter();
    }

    @AfterEach
    public void cleanAll() throws IOException {
        handler.flush();
        handler.close();
        out.close();
    }

    @Test
    public void testSetEncoding() throws Exception {
        handler = new OutputStreamHandler();
        handler.setErrorManager(AssertingErrorManager.of());
        handler.setEncoding("UTF-8");
        Assertions.assertEquals("UTF-8", handler.getEncoding());
    }

    @Test
    public void testSetEncodingOnOutputStream() throws Exception {
        handler = new ConsoleHandler(Target.CONSOLE, NO_FORMATTER);
        handler.setErrorManager(AssertingErrorManager.of());
        handler.setWriter(out);
        handler.setEncoding("UTF-8");
        Assertions.assertEquals("UTF-8", handler.getEncoding());
        handler.publish(new ExtLogRecord(Level.INFO, "Hello World", getClass().getName()));
        Assertions.assertEquals("Hello World", out.toString());
    }

    @Test
    public void testSetNullEncodingOnOutputStream() throws Exception {
        handler = new OutputStreamHandler(NO_FORMATTER);
        handler.setErrorManager(AssertingErrorManager.of());
        handler.setWriter(out);
        handler.setEncoding(null);
        handler.publish(new ExtLogRecord(Level.INFO, "Hello World", getClass().getName()));
        Assertions.assertEquals("Hello World", out.toString());
    }

}
