/*
 * 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.products.ov.validation.services.input;

import com.googlecode.jcsv.reader.CSVReader;
import com.googlecode.jcsv.reader.internal.CSVReaderBuilder;
import com.scytl.products.oscore.logging.api.domain.Level;
import com.scytl.products.oscore.logging.api.domain.LogContent;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.ov.log.ValidationLogConstants;
import com.scytl.products.ov.log.ValidationLogEvents;
import com.scytl.products.ov.mixnet.commons.beans.VoteWithProof;
import com.scytl.products.ov.validation.ValidationException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * A class in charge of reading the input CSV with auditable votes.
 */
public class VotesWithProofReader {

  private final VoteWithProofEntryParser entryParser;
  private final SecureLoggingWriter secureLog;

  @Autowired
  public VotesWithProofReader(VoteWithProofEntryParser entryParser, SecureLoggingWriter secureLog) {
    this.entryParser = entryParser;
    this.secureLog = secureLog;
  }

  public List<VoteWithProof> read(File votesWithProofFile, String electionEventId,
      String ballotBoxId) throws ValidationException {

    try (Reader reader = new FileReader(votesWithProofFile.toString());
        CSVReader<VoteWithProof> votesWithProofReader = new CSVReaderBuilder<VoteWithProof>(
            reader).entryParser(entryParser).build()) {
      return votesWithProofReader.readAll();
    } catch (IOException e) {
      secureLog.log(Level.ERROR, new LogContent.LogContentBuilder()
          .objectId(ballotBoxId)
          .logEvent(ValidationLogEvents.VOTES_WITH_PROOF_READING_FAILURE)
          .user("adminID")
          .electionEvent(electionEventId)
          .additionalInfo(ValidationLogConstants.FILE_NAME,
              String.valueOf(votesWithProofFile.getAbsolutePath()))
          .additionalInfo(ValidationLogConstants.INFO_ERR_DESC, e.getMessage())
          .createLogInfo());
      throw new ValidationException(ValidationLogEvents.VOTES_WITH_PROOF_READING_FAILURE.getInfo(),
          e);
    }
  }
}
