package fr.emse.gitlab.saref.utils;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;

import fr.emse.gitlab.saref.Constants;
import fr.emse.gitlab.saref.SAREFPipelineException;
import fr.emse.gitlab.saref.entities.tests.TestCase;
import fr.emse.gitlab.saref.entities.tests.TestCase.Status;
import fr.emse.gitlab.saref.entities.tests.TestSuite;
import fr.emse.gitlab.saref.entities.tests.TestSuites;

/**
 * Appends to a TestSuites
 * 
 * @author maxime.lefrancois
 *
 */
public class TestSuitesAppender extends AppenderSkeleton {

	private TestSuites testSuites;

	/**
	 * Instantiate a TestSuitesAppender
	 */
	public TestSuitesAppender(TestSuites testSuites) {
		this.testSuites = testSuites;
	}

	/**
	 * This method is called by the {@link AppenderSkeleton#doAppend} method.
	 * 
	 */
	public void append(LoggingEvent event) {
		Level level = event.getLevel();
		if(level.isGreaterOrEqual(Level.INFO)) {
			String loggerName = event.getLoggerName().substring(Constants.LOGGER_BASE.length()+1);
			TestSuite testSuite = testSuites.get(loggerName);
			TestCase testCase = new TestCase(event.getMessage().toString());
			if(level.equals(Level.WARN)) {
				testCase.setStatus(Status.FAILURE);
				ThrowableInformation info = event.getThrowableInformation();
				if(info!=null) {
					Throwable throwable = info.getThrowable();
					String type;
					if(throwable instanceof SAREFPipelineException) {
						SAREFPipelineException exception = (SAREFPipelineException) throwable;
						type = exception.getType();
					} else {
						type = info.getThrowable().getClass().getSimpleName();
					}
					String message = info.getThrowable().getMessage();
					testCase.setFailure(type, message);
					testCase.setSystemErr(String.join("\n", event.getThrowableStrRep()));
				}
			}
			if(level.equals(Level.ERROR)) {
				testCase.setStatus(Status.ERROR);
				ThrowableInformation info = event.getThrowableInformation();
				if(info!=null) {
					Throwable throwable = info.getThrowable();
					String type;
					if(throwable instanceof SAREFPipelineException) {
						SAREFPipelineException exception = (SAREFPipelineException) throwable;
						type = exception.getType();
					} else {
						type = info.getThrowable().getClass().getSimpleName();
					}
					String message = info.getThrowable().getMessage();
					testCase.setError(type, message);
					testCase.setSystemErr(String.join("\n", event.getThrowableStrRep()));
				}
			}
			testSuite.addTestcase(testCase);
		}
	}

	public synchronized void close() {
		if (this.closed)
			return;
		this.closed = true;
	}

	public boolean requiresLayout() {
		return false;
	}


}
