/*
 * 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.event.SecureLoggingEvent;
import com.scytl.slogger.event.SecurePatternLayout;

import java.util.LinkedList;
import java.util.List;

/**
 * Processor that activates a given event processor each a certain amount of log entries.
 */
public class CounterLoggingEventProcessor implements LoggingEventProcessor {

  private static final int NUMBER_LOG_LINES = 50;

  private final int numberLogLines;

  private int currentNumberLogLines;

  private final LoggingEventProcessor eventProcessor;

  /**
   * Constructor.
   *
   * @param numberLogLines the number of log lines
   * @param eventProcessor the event processor.
   */
  public CounterLoggingEventProcessor(final int numberLogLines,
      final LoggingEventProcessor eventProcessor) {
    this.numberLogLines = numberLogLines;
    this.eventProcessor = eventProcessor;
  }

  /**
   * Constructor.
   *
   * @param eventProcessor the event processor.
   */
  public CounterLoggingEventProcessor(final LoggingEventProcessor eventProcessor) {
    this(NUMBER_LOG_LINES, eventProcessor);
  }

  @Override
  public void killProcessor() throws EventProcessorException {}

  @Override
  public List<SecureLoggingEvent> processEvent(final SecureLoggingEvent loggingEvent,
      final SecurePatternLayout layout) throws EventProcessorException {
    List<SecureLoggingEvent> loggingEventList = new LinkedList<>();

    if (numberLogLines > 0) {
      currentNumberLogLines++;
      if (currentNumberLogLines >= numberLogLines) {
        currentNumberLogLines = 0;
        loggingEventList.addAll(eventProcessor.processEvent(loggingEvent, layout));
      }
    }

    return loggingEventList;

  }

  /**
   * Resets the counter.
   */
  public void resetCounter() {
    currentNumberLogLines = 0;
  }

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

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