package org.xbib.logging.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextConfigurator;
import org.xbib.logging.handlers.FileHandler;

public class TestLogContextConfigurator implements LogContextConfigurator {

    public TestLogContextConfigurator() {
        this(true);
    }

    TestLogContextConfigurator(final boolean assumedJul) {
        if (assumedJul) {
            configure(null);
        }
    }

    @Override
    public void configure(final LogContext logContext, final InputStream inputStream) {
        configure(logContext);
    }

    private static void configure(final LogContext logContext) {
        if (Boolean.getBoolean("org.xbib.logging.test.configure")) {
            final Logger rootLogger;
            if (logContext == null) {
                rootLogger = Logger.getLogger("");
            } else {
                rootLogger = logContext.getLogger("");
            }
            try {
                final String fileName = System.getProperty("test.log.file.name");
                final FileHandler handler = new FileHandler(fileName, false);
                handler.setAutoFlush(true);
                handler.setFormatter(new TestFormatter());
                rootLogger.addHandler(handler);
                rootLogger.setLevel(Level.INFO);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    }

    private static class TestFormatter extends ExtFormatter {

        @Override
        public String format(final ExtLogRecord record) {
            StringWriter stringWriter = new StringWriter();
            /*try (JsonGenerator generator = Json.createGenerator(stringWriter)) {
                generator.writeStartObject();

                generator.write("loggerClassName", record.getLoggerClassName());
                generator.write("level", record.getLevel().toString());
                generator.write("message", record.getMessage());
                generator.writeStartObject("mdc");
                final Map<String, String> mdc = record.getMdcCopy();
                mdc.forEach(generator::write);
                generator.writeEnd(); // end MDC

                generator.writeEnd(); // end object
                generator.flush();
                stringWriter.write(System.lineSeparator());
                return stringWriter.toString();
            }*/
            return stringWriter.toString();
        }
    }
}
