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

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

/**
 * Receiver used to parse secure log files. It uses LoggingEventValidator to verify the consistency
 * of each log entry.
 */
public class ValidatorLogFilePatternReceiver extends LogFilePatternReceiver {

  /**
   * The validator.
   */
  protected final LoggingEventValidator validator;

  /**
   * The layout.
   */
  protected final SecurePatternLayout layout;

  private EventValidatorException exception;

  /**
   * Constructor.
   *
   * @param validator the validator
   * @param layout the layout.
   */
  public ValidatorLogFilePatternReceiver(final LoggingEventValidator validator,
      final SecurePatternLayout layout) {
    this.validator = validator;
    this.layout = layout;
  }

  @Override
  public void doPost(final ValidatorLoggingEvent event) {

    try {
      if (event.isMalformed()) {
        getLogger().info("Line ignored: " + event.getRenderedMessage());
      } else {
        SecureLoggingEvent wrappedMessage = SecureLoggingEvent.newClientInstance(event);
        validator.validateEvent(wrappedMessage, layout);
      }
    } catch (EventValidatorException e) {
      if (exception == null) {
        exception = e;
      }
      super.shutdown();
    }
  }

  /**
   * @return Returns the exception.
   */
  public EventValidatorException getException() {
    return exception;
  }

}
