/*
 * 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.commons.sign;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.KeyPair;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;

public class CSVSignerTest {

    private static CSVSigner sut;

    private static KeyPair keyPairForSigning;

    private static Path sourceCSV = Paths.get("src/test/resources/example.csv");

    private static Path sourceCSVEmpty = Paths.get("src/test/resources/emptyExample.csv");

    private static Path outputCSV = Paths.get("target/example.csv");

    private static Path outputCSVEmpty = Paths.get("target/emptyExample.csv");

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @BeforeClass
    public static void setUp() throws GeneralCryptoLibException, IOException {

        sut = new CSVSigner();
        AsymmetricService asymmetricService = new AsymmetricService();
        keyPairForSigning = asymmetricService.getKeyPairForSigning();
        Files.copy(sourceCSV, outputCSV, StandardCopyOption.REPLACE_EXISTING);
        Files.copy(sourceCSVEmpty, outputCSVEmpty, StandardCopyOption.REPLACE_EXISTING);

    }

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

        int numberLines = Files.readAllLines(outputCSV).size();
        sut.sign(keyPairForSigning.getPrivate(), outputCSV);

        assertThat(Files.readAllLines(outputCSV).size(), is(numberLines + 2));
    }

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

        int numberLines = Files.readAllLines(outputCSVEmpty).size();
        sut.sign(keyPairForSigning.getPrivate(), outputCSVEmpty);

        assertThat(Files.readAllLines(outputCSVEmpty).size(), is(numberLines + 2));
    }

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

        expectedException.expect(IOException.class);
        sut.sign(keyPairForSigning.getPrivate(), Paths.get("blabla.csv"));
    }

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

        expectedException.expect(IOException.class);
        sut.sign(keyPairForSigning.getPrivate(), null);
    }
}
