/*
 * 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 java.io.File;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Sequential file name policy.
 */
public class SequentialFileNamePolicy extends LogFileNamePolicy {

  private static final String DOT = ".";

  private static final String SEPARATOR = "-";

  private final String baseFilePrefix;

  private final String baseFileSuffix;

  /**
   * Constructor.
   *
   * @param file the file.
   */
  public SequentialFileNamePolicy(final File file) {
    super(file);

    String fileStr = getBaseFileName().getAbsolutePath();
    int index = fileStr.lastIndexOf(DOT);
    if (index < 0) {
      this.baseFilePrefix = fileStr;
      this.baseFileSuffix = "";
    } else {
      this.baseFilePrefix = fileStr.substring(0, index);
      this.baseFileSuffix = fileStr.substring(index);
    }
  }

  @Override
  public File currentLogFile() throws LogFileNamePolicyException {
    return lastLogFile();
  }

  @Override
  public File lastLogFile() {
    int index = lastLogFileIndex();

    if (index < 0) {
      return null;
    } else {
      return new File(baseFilePrefix + SEPARATOR + index + baseFileSuffix);
    }
  }

  @Override
  public Iterator<File> logFiles() {

    return new Iterator<File>() {

      private int index = 0;

      @Override
      public boolean hasNext() {

        File file = new File(baseFilePrefix + SEPARATOR + index + baseFileSuffix);

        return file.exists();
      }

      @Override
      public File next() {

        File file = new File(baseFilePrefix + SEPARATOR + index + baseFileSuffix);

        if (!file.exists()) {
          throw new NoSuchElementException();
        }

        index++;
        return file;
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }

    };

  }

  @Override
  public File nextLogFile() {
    int index = lastLogFileIndex();

    return new File(baseFilePrefix + SEPARATOR + (index + 1) + baseFileSuffix);
  }

  private int lastLogFileIndex() {
    int index = 0;
    String currentFile = baseFilePrefix + SEPARATOR + index + baseFileSuffix;
    while (new File(currentFile).exists()) {
      index++;
      currentFile = baseFilePrefix + SEPARATOR + index + baseFileSuffix;
    }

    return index - 1;
  }
}
