/*
 * 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.sdm.application.service;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class HashServiceTest {

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

    private static final byte[] TEST_BYTES = "test".getBytes(StandardCharsets.UTF_8);

    private static final String TEST_BYTES_B64_HASH = "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=";

    private static final String TEST_FILE_TO_HASH = "fileToHash";

    private static Path fileToHash;

    private static HashService hashService;

    @BeforeClass
    public static void setUp() throws Exception {
        hashService = new HashService();
        fileToHash = Files.createTempFile(TEST_FILE_TO_HASH, null);
        fileToHash.toFile().deleteOnExit();
        Files.write(fileToHash, TEST_BYTES );
    }

    @Test
    public void testHashFileHappyPath() throws Exception {
        String fileHash = hashService.getB64FileHash(fileToHash);
        assertEquals(TEST_BYTES_B64_HASH, fileHash);
    }

    @Test
    public void testHashBytesHappyPath() throws HashServiceException {
        String bytesHash = hashService.getB64Hash(TEST_BYTES);
        assertEquals(TEST_BYTES_B64_HASH, bytesHash);
    }

    @Test
    public void testHashFileDoesNotExistThrowException() throws HashServiceException {
        Path wrongPath = Paths.get("wrongPath");
        expectedException.expect(HashServiceException.class);
        expectedException.expectMessage("Error computing the hash of " + wrongPath.toString());
        hashService.getB64FileHash(wrongPath);
    }

    @Test
    public void testHashBytesNoDataToHash() throws HashServiceException {
        byte[] dataToHash = null;
        expectedException.expect(HashServiceException.class);
        expectedException.expectMessage("Error computing a hash with provided bytes");
        hashService.getB64Hash(dataToHash);
    }
}