/*
 * 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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Base64;

import org.springframework.stereotype.Service;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.primitives.PrimitivesServiceAPI;
import com.scytl.cryptolib.primitives.service.PollingPrimitivesServiceFactory;

@Service
public class HashService {

    private final PrimitivesServiceAPI primitivesService;

    /**
     * Constructor.
     * 
     * @throws GeneralCryptoLibException
     */
    public HashService() throws GeneralCryptoLibException {
        primitivesService = new PollingPrimitivesServiceFactory().create();
    }

    /**
     * Get a B64 encoded hash of the provided file.
     * 
     * @param filePath
     *            the file to hash.
     * @return the encoded B64 file hash.
     * @throws HashServiceException
     *             if there is an error hashing the data.
     */
    public String getB64FileHash(Path filePath) throws HashServiceException {
        try (InputStream fileIn = new FileInputStream(filePath.toString())) {
            return Base64.getEncoder().encodeToString(primitivesService.getHash(fileIn));
        } catch (IOException | GeneralCryptoLibException e) {
            throw new HashServiceException("Error computing the hash of " + filePath.toString(), e);
        }
    }

    /**
     * Get a B64 encoded hash of the provided bytes.
     * 
     * @param dataToHash
     *            the bytes to hash.
     * @return the hashed bytes B64 encoded.
     * @throws HashServiceException
     *             if there is an error hashing the data.
     */
    public String getB64Hash(byte[] dataToHash) throws HashServiceException {
        try {
            byte[] hashBytes = primitivesService.getHash(dataToHash);
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (GeneralCryptoLibException e) {
            throw new HashServiceException("Error computing a hash with provided bytes", e);
        }
    }
}
