/*
 * 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.util;

import com.scytl.slogger.CleanDirProvider;
import com.scytl.slogger.SecureLoggerException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

import junit.framework.TestCase;

public abstract class LogValidatorTest extends TestCase {

  private String _certificateFile;

  private String _logFile;

  private String _logPattern;

  private String _verifyPattern;

  public void testGetLogFiles() throws IOException, SecureLoggerException {
    String[] args = new String[] {"-l", _logFile};
    Iterator<File> files = LogValidator.getLogFiles(args);
    while (files.hasNext()) {
      assertNotNull(files.next());
    }
  }

  public void testLogValidator() throws Exception {

    String[] args = new String[] {"-c", _certificateFile, "-l", _logFile, "-e",
        StandardCharsets.UTF_8.name(), "-p", _logPattern, "-v", _verifyPattern, "-o",
        CleanDirProvider.getCleanedTmpDir().getAbsolutePath()};
    LogValidator.main(args);
    File errorFile = new File(CleanDirProvider.getTmpDir(), LogValidator.ERROR_FILE);
    assertNull(lastLogLine(errorFile, 0));
  }

  protected abstract String getBaseFilename();

  protected abstract String getCertificate();

  protected abstract String getLastLogFile();

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    _certificateFile =
        Thread.currentThread().getContextClassLoader().getResource(getCertificate()).getFile();
    _logFile = new File(new File(_certificateFile).getParent(), getBaseFilename()).toURI().toURL()
        .getFile();

    _logPattern = "%d %p - %C (%F:%L) [%t] - %m%n";
    _verifyPattern = "TIMESTAMP LEVEL - CLASS (FILE:LINE) [THREAD] - MESSAGE";
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
    CleanDirProvider.deleteTmpDir();
  }

  private String lastLogLine(final File log, final int expectedLines) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(log));
    try {
      String line = null;
      String lastLine = null;
      int lines = 0;
      while ((line = br.readLine()) != null) {
        lastLine = line;
        lines++;
      }

      if (expectedLines >= 0) {
        assertEquals(log.getAbsolutePath() + ". Expected log lines: " + expectedLines
            + " . Existing log lines: " + lines, expectedLines, lines);
      }
      return lastLine;
    } finally {
      br.close();
    }
  }
}
