/*
 * 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.hmac.encrypted.signed;

import com.scytl.slogger.crypto.SecureLoggerCryptographyProvider;
import com.scytl.slogger.event.SecureLoggingEvent;
import com.scytl.slogger.event.SecureMessageProperties;
import com.scytl.slogger.event.SecurePatternLayout;
import com.scytl.slogger.validator.EventValidatorException;
import com.scytl.slogger.validator.hmac.encrypted.EncryptedHMacEventValidator;
import com.scytl.slogger.validator.signature.SignatureEventValidator;

import java.security.PrivateKey;
import java.util.Map;

/**
 * Signed encrypted HMAC validator.
 */
public class SignedEncryptedHMacEventValidator extends EncryptedHMacEventValidator {

  private final SignatureEventValidator signatureEventValidator;

  /**
   * Constructor.
   *
   * @param signatureEventValidator the signature event validator
   * @param cipherPrivateKey the cipher private key
   * @param cryptographyProvider the cryptography provider.
   */
  public SignedEncryptedHMacEventValidator(final SignatureEventValidator signatureEventValidator,
      final PrivateKey cipherPrivateKey,
      final SecureLoggerCryptographyProvider cryptographyProvider) {
    super(cipherPrivateKey, cryptographyProvider);
    this.signatureEventValidator = signatureEventValidator;
  }

  @Override
  public void validateEvent(final SecureLoggingEvent event, final SecurePatternLayout layout)
      throws EventValidatorException {
    super.validateEvent(event, layout);

    Map<String, String> eventProperties = event.getSecureMessage().properties();
    if (eventProperties.containsKey(SecureMessageProperties.ENCRYPTED_SESSION_KEY)) {
      if (!eventProperties.containsKey(SecureMessageProperties.SIGNATURE)) {
        throw new EventValidatorException("Signature expected: " + layout.format(event));
      }
    }

    signatureEventValidator.validateEvent(event, layout);
  }
}
