/*
 * 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.tallying.commons.io.writer;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.Security;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;
import com.scytl.products.ov.commons.sign.MetadataFileSigner;
import com.scytl.products.ov.tallying.command.TallyingHolder;

public class SignResultWriterTest {

    private static final String CONTEST_ID = "27aa7af87de444758e58623b88431d6b";

    private static final String TALLYING_OUTPUT_PATH = "target/test-classes/tally";

    @Rule
    public final TemporaryFolder folder = new TemporaryFolder();

    @BeforeClass
    public static void setUp() {
        Security.addProvider(new BouncyCastleProvider());
    }

    @AfterClass
    public static void removeBouncyCastleProvider() {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }

    @Test
    public void sign_output_correctly() throws IOException, GeneralCryptoLibException {

        FileUtils.copyDirectory(new File(TALLYING_OUTPUT_PATH), folder.getRoot());

        final Path talliedOutputPath = Paths.get(folder.getRoot().getAbsolutePath(), CONTEST_ID + ".csv");

        final TallyingHolder holder = initTallyingHolder(folder.getRoot());

        SignResultWriter signResultWriter = new SignResultWriter(new MetadataFileSigner(new AsymmetricService()));
        signResultWriter.signOutput(talliedOutputPath, holder);

        assertTrue(Paths.get(folder.getRoot().getPath(), CONTEST_ID + ".csv.metadata").toFile().exists());
    }

    private TallyingHolder initTallyingHolder(final File tallyingOutputDirPath) throws GeneralCryptoLibException {

        TallyingHolder holder = new TallyingHolder();
        holder.setOutputDir(Paths.get(tallyingOutputDirPath.getAbsolutePath(), "tally"));
        holder.setTenantId("100");
        holder.setElectionEventId("1234");
        holder.setBallotBoxId("1234");

        PrivateKey privateKey = new AsymmetricService().getKeyPairForSigning().getPrivate();

        holder.setSignatureKey(privateKey);

        return holder;
    }
}
