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

import static java.nio.file.Files.newBufferedReader;
import static java.util.Collections.emptyMap;

import com.scytl.slogger.event.SecureMessage;
import com.scytl.slogger.event.SecureMessageProperties;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * Log file searcher.
 */
public class LogFileSearcher {

  private final File logFile;

  private byte[] lastHMac = {};

  private byte[] lastEncryptedSessionKey;

  /**
   * Constructor.
   *
   * @param logFile the log file.
   */
  public LogFileSearcher(final File logFile) {
    this.logFile = logFile;
  }

  /**
   * Returns the last encrypted session key.
   *
   * @return the last encrypted session key.
   */
  public byte[] getLastEncryptedSessionKey() {
    if (lastEncryptedSessionKey == null) {
      return null;
    }

    return lastEncryptedSessionKey.clone();
  }

  /**
   * Returns the last HMAC.
   *
   * @return the last HMAC.
   */
  public byte[] getLastHMac() {
    return lastHMac.clone();
  }

  /**
   * Processes the log file.
   *
   * @throws SecureLoggerException failed to process the log file.
   */
  public void processLogFile() throws SecureLoggerException {
    if (logFile == null || logFile.length() == 0) {
      return;
    }

    try (BufferedReader reader = newBufferedReader(logFile.toPath(), StandardCharsets.UTF_8)) {
      Map<String, String> properties = emptyMap();
      String encryptedSessionKey = null;

      String line;
      while ((line = reader.readLine()) != null) {
        properties = SecureMessage.newRenderedInstance(line).properties();
        encryptedSessionKey = properties.getOrDefault(SecureMessageProperties.ENCRYPTED_SESSION_KEY,
            encryptedSessionKey);
      }

      lastHMac = Base64.getDecoder().decode(properties.get(SecureMessageProperties.HMAC));
      if (encryptedSessionKey != null) {
        lastEncryptedSessionKey =
            Base64.getDecoder().decode(encryptedSessionKey.getBytes(StandardCharsets.UTF_8));
      }
    } catch (IOException e) {
      throw new SecureLoggerException("Failed to process the log file.", e);
    }
  }
}
