package org.xbib.logging.handlers;

import java.io.Console;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import org.xbib.logging.errormanager.HandlerErrorManager;
import org.xbib.logging.io.UncloseableOutputStream;
import org.xbib.logging.io.UncloseableWriter;
import org.xbib.logging.util.CharsetUtil;

/**
 * A console handler which writes to {@code System.out} by default.
 */
public class ConsoleHandler extends OutputStreamHandler {

    private static final OutputStream out = System.out;

    private static final OutputStream err = System.err;

    /**
     * The target stream type.
     */
    public enum Target {

        /**
         * The target for {@link System#out}.
         */
        SYSTEM_OUT,
        /**
         * The target for {@link System#err}.
         */
        SYSTEM_ERR,
        /**
         * The target for {@link System#console()}.
         */
        CONSOLE,
    }

    private static final PrintWriter console;

    private final ErrorManager localErrorManager = new HandlerErrorManager(this);

    static {
        final Console con = System.console();
        console = con == null ? null : con.writer();
    }

    /**
     * Construct a new instance.
     */
    public ConsoleHandler() {
        this(nullFormatter());
    }

    /**
     * Construct a new instance.
     *
     * @param formatter the formatter to use
     */
    public ConsoleHandler(final Formatter formatter) {
        this(console == null ? Target.SYSTEM_OUT : Target.CONSOLE, formatter);
    }

    /**
     * Construct a new instance.
     *
     * @param target the target to write to, or {@code null} to start with an uninitialized target
     */
    public ConsoleHandler(final Target target) {
        this(target, nullFormatter());
    }

    /**
     * Construct a new instance.
     *
     * @param target    the target to write to, or {@code null} to start with an uninitialized target
     * @param formatter the formatter to use
     */
    public ConsoleHandler(final Target target, final Formatter formatter) {
        super(formatter);
        setCharset(CharsetUtil.consoleCharset());
        switch (target) {
            case SYSTEM_OUT:
                setOutputStream(wrap(out));
                break;
            case SYSTEM_ERR:
                setOutputStream(wrap(err));
                break;
            case CONSOLE:
                setWriter(wrap(console));
                break;
            default:
                throw new IllegalArgumentException();
        }
    }

    /**
     * Set the target for this console handler.
     *
     * @param target the target to write to, or {@code null} to clear the target
     */
    public void setTarget(Target target) {
        final Target t = (target == null ? console == null ? Target.SYSTEM_OUT : Target.CONSOLE : target);
        switch (t) {
            case SYSTEM_OUT:
                setOutputStream(wrap(out));
                break;
            case SYSTEM_ERR:
                setOutputStream(wrap(err));
                break;
            case CONSOLE:
                setWriter(wrap(console));
                break;
            default:
                throw new IllegalArgumentException();
        }
    }

    @Override
    public void setErrorManager(final ErrorManager em) {
        if (em == localErrorManager) {
            // ignore to avoid loops
            super.setErrorManager(new ErrorManager());
            return;
        }
        super.setErrorManager(em);
    }

    private static final String ESC = Character.toString(27);

    /**
     * Get the local error manager. This is an error manager that will publish errors to this console handler.
     * The console handler itself should not use this error manager.
     *
     * @return the local error manager
     */
    public ErrorManager getLocalErrorManager() {
        return localErrorManager;
    }

    private static OutputStream wrap(final OutputStream outputStream) {
        return outputStream == null ? null
                : outputStream instanceof UncloseableOutputStream ? outputStream : new UncloseableOutputStream(outputStream);
    }

    private static Writer wrap(final Writer writer) {
        return writer == null ? null : writer instanceof UncloseableWriter ? writer : new UncloseableWriter(writer);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setOutputStream(final OutputStream outputStream) {
        super.setOutputStream(wrap(outputStream));
    }

    /**
     * Determine whether the console exists.
     * If the console does not exist, then the standard output stream will be used when {@link Target#CONSOLE} is
     * selected as {@linkplain #setTarget(Target) the output target}.
     *
     * @return {@code true} if there is a console, {@code false} otherwise
     */
    public static boolean hasConsole() {
        return console != null;
    }

    /**
     * Determine whether the console supports truecolor output.
     * This call may be expensive, so the result should be captured for the lifetime of any formatter making use of
     * this information.
     *
     * @return {@code true} if the console exists and supports truecolor output; {@code false} otherwise
     */
    public static boolean isTrueColor() {
        if (!hasConsole()) {
            return false;
        }
        final String colorterm = System.getenv("COLORTERM");
        return colorterm != null && (colorterm.contains("truecolor") || colorterm.contains("24bit"));
    }
}
