/*
 * 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.vv.infrastructure.log;

import java.math.BigInteger;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.primitives.PrimitivesServiceAPI;
import com.scytl.cryptolib.primitives.service.PrimitivesService;
import com.scytl.products.ov.commons.beans.domain.model.vote.Vote;
import com.scytl.products.ov.commons.beans.exceptions.SecureLoggerHelperException;
import com.scytl.products.ov.commons.crypto.InputDataFormatterService;

/**
 * Computes the hash of a vote.
 */
public class SecureLoggerHelper {

    @Inject
    private InputDataFormatterService inputDataFormatterService;

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

    /**
     * Compute hash for the vote.
     * 
     * @param vote
     *            the vote.
     * @return the hash of the vote.
     */
    public String hash(Vote vote) {
        String voteHash = "";
        if (vote != null) {
            // this is for avoid concurrency problems due to this operation is
            // not thread safe.
            PrimitivesServiceAPI primitivesService;
            try {
                primitivesService = new PrimitivesService();
            } catch (GeneralCryptoLibException e) {
                throw new SecureLoggerHelperException("Error trying to create PrimitivesService.", e);
            }
            try {
                byte[] hashBytes =
                    primitivesService.getHash(inputDataFormatterService.concatenate(vote.getElectionEventId(),
                        vote.getVotingCardId(), vote.getEncryptedOptions(), vote.getEncryptedPartialChoiceCodes(),
                        vote.getVerificationCardPublicKey(), vote.getAuthenticationToken(), vote.getSchnorrProof(),
                        vote.getExponentiationProof(), vote.getPlaintextEqualityProof(),
                        vote.getCipherTextExponentiations()));
                voteHash = new BigInteger(hashBytes).toString();
            } catch (GeneralCryptoLibException e) {
                LOG.error("Error computing the hash of the vote", e);
            }
        }
        return voteHash;
    }

}
