/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt'
 * which is part of this source code package
 */

package com.scytl.slogger;

import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.LoggingEvent;

import java.io.InterruptedIOException;

/**
 * Class implements the ErrorHandler interface such that all error messages are printed on
 * {@code System.err} and to backup appender if provided.
 */
public class SecureErrorHandler implements ErrorHandler {

  private Appender backupAppender;

  /**
   * Constructor.
   */
  public SecureErrorHandler() {}

  @Override
  public void activateOptions() {}

  @Override
  public void error(String message) {
    LogLog.error(message);
    if (backupAppender != null) {
      backupAppender.doAppend(new LoggingEvent(this.getClass().getCanonicalName(),
          Logger.getRootLogger(), Level.ERROR, message, null));
    }
  }

  @Override
  public void error(String message, Exception error, int errorCode) {
    error(message, error, errorCode, null);
  }

  @Override
  public void error(String message, Exception error, int errorCode, LoggingEvent event) {

    if (error instanceof InterruptedIOException || error instanceof InterruptedException) {
      Thread.currentThread().interrupt();
    }

    LogLog.error(message, error);

    if (backupAppender != null) {
      if (event != null) {
        backupAppender.doAppend(event);
      } else {
        backupAppender.doAppend(new LoggingEvent(this.getClass().getCanonicalName(),
            Logger.getRootLogger(), Level.ERROR, message, error));
      }
    }

  }

  @Override
  public void setAppender(Appender appender) {}

  @Override
  public void setBackupAppender(Appender appender) {
    this.backupAppender = appender;
  }

  @Override
  public void setLogger(Logger logger) {}
}
