/*
 * 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;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.primitives.PrimitivesServiceAPI;
import com.scytl.products.ov.tallying.commons.exception.TallyingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;

public class HashService {

    private static final Logger LOG = LoggerFactory.getLogger("std");

    private final PrimitivesServiceAPI primitivesService;

    public HashService(PrimitivesServiceAPI primitivesService) {
        this.primitivesService = primitivesService;
    }

    public String getHash(InputStream csvFileIn, String fileAbsolutePath) throws TallyingException {
        try {
            byte[] hashBytes = primitivesService.getHash(csvFileIn);
            return new BigInteger(1, hashBytes).toString();
        } catch (GeneralCryptoLibException e) {
            String message = "Error computing the hash of " + fileAbsolutePath;
            LOG.error(message, e);
            throw new TallyingException(message, e);
        }
    }

    public String getHash(String fileAbsolutePath) throws TallyingException {
        try(InputStream fileIn = new FileInputStream(fileAbsolutePath)) {
            return getHash(fileIn, fileAbsolutePath);
        } catch (IOException e) {
            String message = "Error computing the hash of " + fileAbsolutePath;
            LOG.error(message, e);
            throw new TallyingException(message, e);
        }
    }
}
