/*
 * 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 require */
/* global CL */
/* global forge */

module.exports = (function() {

    'use strict';

    var _ = require('lodash');
    var config = require('../client/config.js');
    var session = require('../client/session.js');

    // derives a single value

    var derive = function(verificationCardId, electionEventId) {
        var deriver = CL.primitives.service.getPbkdfSecretKeyGenerator();
        var converter = new CL.commons.utils.Converters();
        var derivedKeyBase64Encoded = deriver.generateSecret(forge.util.encode64(verificationCardId), forge.util.encode64(electionEventId));
        var derivedKeyAsByteString = forge.util.decode64(derivedKeyBase64Encoded).toString();
        var derivedKeyAsBytes = converter.bytesFromString(derivedKeyAsByteString);
        var derivedKeyAsBigInteger = new forge.jsbn.BigInteger(derivedKeyAsBytes).abs();
        var derivedKey = derivedKeyAsBigInteger.toString();

        return derivedKey;
    };

    // derives ballot casting key

    var generateBallotCastingKey = function() {

        var derivedKey = derive(session('verificationCardId'), config('electionEventId'));
        var derivedKeyTruncated = derivedKey.substring(0, 9);

        if (derivedKeyTruncated.length < 9){
            derivedKeyTruncated = _.padStart(derivedKeyTruncated, 9, '0');
        }

        return derivedKeyTruncated;
    };

    return generateBallotCastingKey;

}());