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

import com.scytl.slogger.CleanDirProvider;

import java.io.File;
import java.util.Iterator;

import junit.framework.TestCase;

public class SequentialFileNamePolicyTest extends TestCase {

  private static final int LOG_FILES = 100;

  private static final String LOG_FILE = "sequential-test.log";

  private static final String INDEX = "INDEX";

  private static final String LOG_FILE_X = "sequential-test-" + INDEX + ".log";

  private File _baseLogFile;

  public void testFilePolicy() throws Exception {
    SequentialFileNamePolicy policy = new SequentialFileNamePolicy(_baseLogFile);

    // No log files
    assertFalse(policy.logFiles().hasNext());
    assertEquals(policy.nextLogFile(),
        new File(CleanDirProvider.getTmpDir().getAbsolutePath(), LOG_FILE_X.replace(INDEX, "0")));
    assertNull(policy.lastLogFile());

    // Multiple log files
    for (int i = 0; i < LOG_FILES; i++) {
      File nextLogFile = policy.nextLogFile();
      assertTrue(nextLogFile.createNewFile());
      assertEquals(nextLogFile, policy.lastLogFile());
      int index = 0;
      File lastLogFile = null;
      for (Iterator<File> logFiles = policy.logFiles(); logFiles.hasNext();) {
        lastLogFile = new File(CleanDirProvider.getTmpDir().getAbsolutePath(),
            LOG_FILE_X.replace(INDEX, "" + index));
        assertEquals(logFiles.next(), lastLogFile);
        index++;
      }
      assertEquals(policy.lastLogFile(), lastLogFile);
    }

  }

  @Override
  protected void setUp() throws Exception {
    _baseLogFile = new File(CleanDirProvider.getCleanedTmpDir().getAbsolutePath(), LOG_FILE);
  }

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

}
