/*
 * 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.products.ov.channel.cc.commons.slogger;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.LoggingEvent;

import com.scytl.slogger.SecureLoggerException;

/**
 * Implementation of {@link ErrorTracker}.
 */
class ErrorTrackerImpl implements ErrorTracker {
    private volatile ErrorHandler target;

    private volatile SecureLoggerException exception;

    @Override
    public void activateOptions() {
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.activateOptions();
        }
    }

    @Override
    public void checkNoError() throws SecureLoggerException {
        if (exception != null) {
            throw exception;
        }
    }

    @Override
    public void error(String message) {
        exception = new SecureLoggerException(message);
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.error(message);
        }
    }

    @Override
    public void error(String message, Exception e, int errorCode) {
        exception = new SecureLoggerException(message, e);
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.error(message, e, errorCode);
        }
    }

    @Override
    public void error(String message, Exception e, int errorCode,
            LoggingEvent event) {
        exception = new SecureLoggerException(message, e);
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.error(message, e, errorCode, event);
        }
    }

    @Override
    public void setAppender(Appender appender) {
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.setAppender(appender);
        }
    }

    @Override
    public void setBackupAppender(Appender appender) {
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.setBackupAppender(appender);
        }
    }

    @Override
    public void setLogger(Logger logger) {
        ErrorHandler errorHandler = this.target;
        if (errorHandler != null) {
        	errorHandler.setLogger(logger);
        }
    }

    @Override
    public void setTarget(ErrorHandler target) {
        this.target = target;
    }
}
