package org.xbib.logging.ext.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.ErrorManager;
import org.junit.jupiter.api.Assertions;

public class AssertingErrorManager extends ErrorManager {

    private final int[] allowedCodes;

    private AssertingErrorManager() {
        this.allowedCodes = null;
    }

    private AssertingErrorManager(final int... allowedCodes) {
        this.allowedCodes = allowedCodes;
    }

    public static AssertingErrorManager of() {
        return new AssertingErrorManager();
    }

    public static AssertingErrorManager of(final int... allowedCodes) {
        return new AssertingErrorManager(allowedCodes);
    }

    @Override
    public void error(final String msg, final Exception ex, final int code) {
        if (notAllowed(code)) {
            final String codeStr = switch (code) {
                case CLOSE_FAILURE -> "CLOSE_FAILURE";
                case FLUSH_FAILURE -> "FLUSH_FAILURE";
                case FORMAT_FAILURE -> "FORMAT_FAILURE";
                case GENERIC_FAILURE -> "GENERIC_FAILURE";
                case OPEN_FAILURE -> "OPEN_FAILURE";
                case WRITE_FAILURE -> "WRITE_FAILURE";
                default -> "INVALID (" + code + ")";
            };
            try (
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw)) {
                pw.printf("LogManager error of type %s: %s%n", codeStr, msg);
                if (ex != null) {
                    ex.printStackTrace(pw);
                }
                Assertions.fail(sw.toString());
            } catch (IOException e) {
                // This shouldn't happen, but just fail if it does
                e.printStackTrace();
                Assertions.fail(String.format("Failed to print error message: %s", e.getMessage()));
            }
        }
    }

    private boolean notAllowed(final int code) {
        if (allowedCodes != null) {
            for (int allowedCode : allowedCodes) {
                if (code == allowedCode) {
                    return false;
                }
            }
        }
        return true;
    }
}
