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

import com.scytl.slogger.SecureFileAppender;
import com.scytl.slogger.event.SecureLoggingEvent;
import com.scytl.slogger.event.SecurePatternLayout;

import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Processor that logs a new entry each a certain time.
 */
public class TimerLoggingEventProcessor extends BaseLoggingEventProcessor {

  public static final String CHECKPOINT_ENTRY = "Checkpoint Entry";

  private final SecureFileAppender appender;

  private final long milliseconds;

  private Timer timer;

  private TimerTask task;

  /**
   * Constructor. secure file appender
   *
   * @param milliseconds given time to log the special entry
   */
  public TimerLoggingEventProcessor(final SecureFileAppender appender, final long milliseconds) {
    this.appender = appender;
    this.milliseconds = milliseconds;
  }

  @Override
  public void killProcessor() throws EventProcessorException {
    if (timer != null) {
      task.cancel();
      task = null;
      timer.cancel();
      timer = null;
    }
  }

  @Override
  public List<SecureLoggingEvent> startProcessor(final SecurePatternLayout layout)
      throws EventProcessorException {
    if (milliseconds > 0 && timer == null) {
      timer = new Timer("TIMER-LOG", true);
      task = new TimerTaskAdapter();
      timer.schedule(task, milliseconds, milliseconds);
    }
    return new LinkedList<>();
  }

  @Override
  public List<SecureLoggingEvent> stopProcessor(final SecurePatternLayout layout)
      throws EventProcessorException {
    killProcessor();
    return new LinkedList<>();
  }

  /**
   * Resets the timer.
   */
  protected void resetTimer() {
    if (timer != null) {
      task.cancel();
      task = new TimerTaskAdapter();
      timer.schedule(task, milliseconds, milliseconds);
    }
  }

  private void run() {
    appender.append(SecureLoggingEvent.newCheckpointInstance());
  }

  private class TimerTaskAdapter extends TimerTask {
    @Override
    public void run() {
      TimerLoggingEventProcessor.this.run();
    }
  }
}
