/*
 * 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.config.it.verifiers;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.scytl.products.ov.commons.beans.Ballot;
import com.scytl.products.ov.commons.beans.Contest;
import com.scytl.products.ov.commons.beans.ElectionOption;
import com.scytl.products.ov.constants.Constants;
import com.scytl.products.ov.utils.ConfigObjectMapper;

/**
 * A class to execute all validations related with Create Ballot Boxes command
 */
public class EnrichBallotVerifier {

    private final ConfigObjectMapper _mapper = new ConfigObjectMapper();

    /**
     * @param eeidFolder
     * @param inputBallotJSONPath
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    public void enrichBallotValidations(final File eeidFolder, final Path inputBallotJSONPath) throws IOException {

        Ballot oldBallot = _mapper.fromJSONFileToJava(inputBallotJSONPath.toFile(), Ballot.class);
        for (Contest contest : oldBallot.getContests()) {
            for (ElectionOption option : contest.getOptions()) {
                Assert.assertTrue(StringUtils.isEmpty(option.getRepresentation()));
            }
        }

        Path ballotIdFolder = Paths.get(eeidFolder.getAbsolutePath(), Constants.ONLINE_DIRECTORY,
            Constants.ELECTION_INFORMATION_DIRECTORY, Constants.BALLOTS_DIRECTORY, oldBallot.getId());
        File updatedBallotJSONFile = Paths.get(ballotIdFolder.toString(), Constants.ENRICHED_BALLOT_FILENAME).toFile();

        Ballot updatedBallot = _mapper.fromJSONFileToJava(updatedBallotJSONFile, Ballot.class);
        for (Contest contest : updatedBallot.getContests()) {
            for (ElectionOption option : contest.getOptions()) {
                String representation = option.getRepresentation();
                Assert.assertTrue(StringUtils.isNotEmpty(representation));
                Assert.assertTrue(new BigInteger(representation).isProbablePrime(100));
            }
        }

        Path copiedBallotTextsPath = Paths.get(ballotIdFolder.toString(), Constants.ENRICHED_BALLOT_FILENAME);
        Assert.assertTrue(Files.exists(copiedBallotTextsPath));
    }
}
