/*
 * 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 com.scytl.slogger.policy.LogFileNamePolicy;
import com.scytl.slogger.policy.LogFileNamePolicyException;

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

/**
 * File name event processor.
 */
public class FileNameEventProcessor extends BaseLoggingEventProcessor {

  private final LogFileNamePolicy policy;

  private boolean processorStarted;

  /**
   * Constructor.
   *
   * @param policy the policy.
   */
  public FileNameEventProcessor(final LogFileNamePolicy policy) {
    this.policy = policy;
  }

  @Override
  public List<SecureLoggingEvent> processEvent(final SecureLoggingEvent loggingEvent,
      final SecurePatternLayout layout) throws EventProcessorException {

    List<SecureLoggingEvent> result = new LinkedList<>();

    if (processorStarted) {

      try {

        result.add(SecureLoggingEvent.newFileInstance(policy.currentLogFile()));

      } catch (LogFileNamePolicyException e) {
        throw new EventProcessorException(e);
      } finally {
        processorStarted = false;
      }

    }

    result.addAll(super.processEvent(loggingEvent, layout));

    return result;

  }

  @Override
  public List<SecureLoggingEvent> startProcessor(final SecurePatternLayout layout)
      throws EventProcessorException {
    processorStarted = true;
    return super.startProcessor(layout);
  }
}
