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

module.exports = (function() {

    'use strict';

    var jsrsasign = require('jsrsasign');


    var parseEncryptionParams = function(response) {

        try {

            var verificationCardSet = response.verificationCardSet.data ?
                    response.verificationCardSet.data : response.verificationCardSet ;

            var ballotBox = jsrsasign.jws.JWS.parse(response.ballotBox.signature).payloadObj.objectToSign;

            var electoralAuthority = jsrsasign.jws.JWS.parse(response.ballotBox.electoralAuthority.signature).payloadObj.objectToSign;

            return new OV.model.EncryptionParams({
                serializedP: ballotBox.encryptionParameters.p,
                serializedG: ballotBox.encryptionParameters.g,
                serializedOptionsEncryptionKey: electoralAuthority.publicKey,
                serializedChoiceCodesEncryptionKey: verificationCardSet.choicesCodesEncryptionPublicKey
            });

        } catch (e) {
            console.log(e.message);
            throw new Error('Invalid encryption parameters');
        }

    };

    return parseEncryptionParams;

})();
