/*
 * 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 com.scytl.slogger.policy.LogFileNamePolicyException;
import com.scytl.slogger.util.Securities;
import com.scytl.slogger.validator.EventValidatorException;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Configurator;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;

import junit.framework.TestCase;

/**
 *
 */
public abstract class XMLAppenderTester extends TestCase {

  private static final int LOG_TRACES = 1000;

  private static final String TEST_APPENDER = "TEST_APPENDER";

  private static final String TEST_LOGGER = "SECURE";

  private Logger _logger;

  private SecureFileAppender _appender;

  /**
   * @throws EventValidatorException
   * @throws LogFileNamePolicyException
   */
  public void testAppender() throws EventValidatorException, LogFileNamePolicyException {

    for (int i = 0; i < LOG_TRACES; i++) {
      _logger.info("log n. " + i);
    }

    assertEquals(1, countLogFiles());
    LogManager.shutdown();
    verifyLog(_appender);
  }

  /**
   * @return
   */
  protected abstract URL getXMLConfigURL();

  /**
   * @see junit.framework.TestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    Securities.addBouncyCastleProviderIfNecessary();
    Configurator config = new DOMConfigurator();
    config.doConfigure(getXMLConfigURL(), LogManager.getLoggerRepository());
    _logger = Logger.getLogger(TEST_LOGGER);
    _appender = (SecureFileAppender) _logger.getAppender(TEST_APPENDER);
  }

  /**
   * @see junit.framework.TestCase#tearDown()
   */
  @Override
  protected void tearDown() throws Exception {
    try {
      LogManager.shutdown();
      deleteLogFiles();
    } finally {
      Securities.removeBouncyCastleProviderIfNecessary();
    }
  }

  protected abstract void verifyLog(SecureFileAppender secureAppender)
      throws EventValidatorException;

  private int countLogFiles() throws LogFileNamePolicyException {
    int count = 0;
    for (Iterator<File> it = _appender.getLogFileNamePolicy().logFiles(); it.hasNext();) {
      it.next();
      count++;
    }

    return count;
  }

  /**
   * @throws LogFileNamePolicyException
   * @throws IOException
   */
  private void deleteLogFiles() throws LogFileNamePolicyException {
    for (Iterator<File> it = _appender.getLogFileNamePolicy().logFiles(); it.hasNext();) {
      it.next().delete();
    }
  }

}
