/*
 * 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
 */
/* global OV */
/* global CL */
/* global forge */
/* jshint maxlen: 666  */

module.exports = (function() {

    'use strict';

    // validate vote cast response
    // returns: vote cast code
    var validateCastResponse = function(response, credentialCert, voteCastCodeSignerCert, authenticationTokenSignerCert, ballotBoxCert, trustedVotingCardId, trustedElectionEventId, trustedVerificationCardId) {

        var electionEventId = response.electionEventId;
        var votingCardId = response.votingCardId;
        var verificationCardId = response.verificationCardId;

        if(electionEventId !== trustedElectionEventId ||votingCardId !== trustedVotingCardId || verificationCardId !== trustedVerificationCardId)
        {
            throw new Error('Bad vote');
        }

        var voteCastMessage = response.voteCastMessage;
        var authenticationToken = response.voteMessage.authenticationToken;
        var encryptedVote = response.voteMessage.encryptedVote;
        var receiptMessage = response.voteMessage.receiptMessage;


        // verify signatures

        var receiptMessageSignature = receiptMessage.signature;
        var ballotBoxPublicKey = CL.certificates.service.load(ballotBoxCert).getPublicKey();
        if (!OV.verifySignature([receiptMessage.receipt],ballotBoxPublicKey,receiptMessageSignature)) {
            throw new Error('Receipt signature validation failed');
        }


        OV.parseToken(authenticationToken, authenticationTokenSignerCert);
           

        var castMessageSignature = voteCastMessage.signature;
        var castCodePublicKey = CL.certificates.service.load(voteCastCodeSignerCert).getPublicKey();

        if (!OV.verifySignature([voteCastMessage.voteCastCode,verificationCardId],castCodePublicKey,castMessageSignature)) {
            throw new Error('Cast code signature validation failed');
        }

        OV.parseSignedVote(encryptedVote, authenticationToken, votingCardId, electionEventId, credentialCert);

        
        var receiptInput = [encryptedVote.signature, authenticationToken.signature, encryptedVote.verificationCardPKSignature, electionEventId, votingCardId].join('');    
        var calculatedReceiptBase64 = CL.primitives.service.getHash([forge.util.encode64(receiptInput)]);
        
        
        if(calculatedReceiptBase64 !== receiptMessage.receipt)
        {
            throw new Error('Bad receipt');
        }



        return {
            voteCastCode: voteCastMessage.voteCastCode,
            receipt: receiptMessage.receipt,
            receiptSignature: receiptMessage.signature
        };
    };

    return validateCastResponse;

})();
