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

module.exports = (function() {

    'use strict';

    // Stores voting protocol parameters and keys

    var extractCredentials = function(credentialData, pass) {

        var ksObject, ks, voterPrivateKeys,certificateAuth, certificateSign, 
            passb64 = forge.util.encode64(pass);

        try {
            ksObject = JSON.parse(forge.util.decode64(credentialData.data));
        } catch (e) {
            throw new Error('Invalid credential data');
        }

        try {
            ks = new CL.stores.service.loadStore(ksObject);
            voterPrivateKeys = ks.getPrivateKeyChain(passb64);
            certificateAuth = ks.getCertificateBySubject(passb64, 'Auth ' + credentialData.id);  
            certificateSign = ks.getCertificateBySubject(passb64, 'Sign ' + credentialData.id);  
        } catch (e) {
            throw new Error('Could not access keystore');
        }

        return {
            //credentialData.id
            voterPrivateKey: voterPrivateKeys.map['sign'],
            authPrivateKey: voterPrivateKeys.map['auth_sign'],
            certificate: certificateSign,
            certificateAuth: certificateAuth,
            credentialId:credentialData.id
        };

    };

    return extractCredentials;

})();
