/*
 * 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.ei.services.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.exceptions.ConfirmationMessageHashServiceException;
import com.scytl.products.ov.commons.crypto.InputDataFormatterService;
import com.scytl.products.ov.ei.services.domain.model.confirmation.ConfirmationInformation;

/**
 * Generate confirmation message hash.
 */
public class ConfirmationMessageHashService {

    @Inject
    private InputDataFormatterService inputDataFormatterService;

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

    /**
     * Compute hash for the confirmation message.
     * 
     * @param vote
     *            the vote.
     * @return the hash of the vote.
     */
    public String hash(ConfirmationInformation confirmationInformation) {

        // this is for avoid concurrency problems due to this operation is not thread safe.
        PrimitivesServiceAPI primitivesService;
        try {
            primitivesService = new PrimitivesService();
        } catch (GeneralCryptoLibException gcE) {
            throw new ConfirmationMessageHashServiceException("Error trying to create PrimitivesService.", gcE);
        }

        try {
            byte[] hashBytes = primitivesService.getHash(inputDataFormatterService.concatenate(
                confirmationInformation.getCredentialId(), confirmationInformation.getCertificate(),
                confirmationInformation.getConfirmationMessage().getConfirmationKey(),
                confirmationInformation.getConfirmationMessage().getSignature()));
            return new BigInteger(hashBytes).toString();
        } catch (GeneralCryptoLibException e) {
            LOG.error("Error computing the hash of the confirmation information", e);
            return "";
        }
    }

}
