/*
 * 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.cryptolib.interoperation.js.commands.asymmetric;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

import javax.script.ScriptException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;
import com.scytl.cryptolib.interoperation.js.commands.Command;
import com.scytl.cryptolib.interoperation.js.commands.CommandException;
import com.scytl.cryptolib.interoperation.js.constants.AsymmetricConstants;
import com.scytl.cryptolib.interoperation.js.constants.CommonConstants;
import com.scytl.cryptolib.primitives.primes.utils.PemUtils;
import com.scytl.cryptolib.primitives.primes.utils.PrimitivesTestDataGenerator;
import com.scytl.cryptolib.primitives.securerandom.constants.SecureRandomConstants;
import com.scytl.cryptolib.test.tools.utils.CommonTestDataGenerator;

/**
 * Tests the Java-JavaScript interoperation for asymmetric signer applications.
 */
public class TestAsymmetricSigner extends Command {

    private static final Logger LOGGER =
        LoggerFactory.getLogger(TestAsymmetricSigner.class);

    private final Object _namespace;

    private final AsymmetricService _asymmetricService;

    private PublicKey _publicKey;

    private String _publicKeyPem;

    private PrivateKey _privateKey;

    private String _privateKeyPem;

    private byte[] _data;

    private String _dataB64;

    /**
     * Default constructor.
     *
     * @throws CommandException
     *             if the script engine cannot evaluate the asymmetric signer
     *             interoperation tests implemented in JavaScript.
     */
    public TestAsymmetricSigner() throws CommandException {
        super(AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_PATH);

        _namespace = _engine
            .get(AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_NAMESPACE);

        clearExceptionData();

        try {
            _asymmetricService = new AsymmetricService();

            generateInputData();
        } catch (GeneralCryptoLibException e) {
            throw new CommandException.Builder().addCause(e).build();
        }
    }

    /**
     * Digitally signs some data using Java, verifies the result using
     * JavaScript, digitally signs the same data using JavaScript and verifies
     * the result using Java. If no exceptions are thrown and the signatures can
     * verified , then the interoperation test for asymmetric signer
     * applications was successful.
     *
     * @throws CommandException
     *             if a JavaScript method cannot be found, a cryptographic
     *             operation fails or a signature verification operation yields
     *             a value of false.
     */
    @Override
    public void execute() throws CommandException {

        String signatureB64 = signDataUsingJava();

        verifySignatureUsingJavaScript(signatureB64);

        signatureB64 = signDataUsingJavaScript();

        verifySignatureUsingJava(signatureB64);

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "INTEROPERATION TEST FOR ASYMMETRIC SIGNER WAS SUCCESSFUL.");
    }

    private void generateInputData() throws GeneralCryptoLibException {

        KeyPair keyPair = _asymmetricService.getKeyPairForSigning();

        _publicKey = keyPair.getPublic();
        _publicKeyPem = PemUtils.publicKeyToPem(_publicKey);
        putExceptionData("Public key (PEM format) [Java]", _publicKeyPem);

        _privateKey = keyPair.getPrivate();
        _privateKeyPem = PemUtils.privateKeyToPem(_privateKey);
        putExceptionData("Private key (PEM format) [Java]",
            _privateKeyPem);

        _data = PrimitivesTestDataGenerator
            .getByteArray(CommonTestDataGenerator.getInt(1,
                SecureRandomConstants.MAXIMUM_GENERATED_BYTE_ARRAY_LENGTH));
        _dataB64 = Base64.getEncoder().encodeToString(_data);
        putExceptionData("Data to sign (Base64 encoded) [Java]", _dataB64);
    }

    private String signDataUsingJava() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Digitally signing data, using Java...");

        try {
            return Base64.getEncoder().encodeToString(
                _asymmetricService.sign(_privateKey, _data));
        } catch (GeneralCryptoLibException e) {
            throw buildExceptionWithData(
                "Could not digitally sign data, using Java.", e);
        }
    }

    private void verifySignatureUsingJavaScript(final String signatureB64)
            throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Verifying digital signature, using JavaScript...");

        try {
            getInvocable().invokeMethod(_namespace,
                AsymmetricConstants.JS_ASYMMETRIC_SIGNATURE_VERIFICATION_FUNCTION,
                signatureB64, _publicKeyPem, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_NAMESPACE
                        + "."
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNATURE_VERIFICATION_FUNCTION
                        + " in resources file "
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not verify Java generated digital signature, using JavaScript.",
                e);
        }
    }

    private String signDataUsingJavaScript() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Digitally signing data, using JavaScript...");

        try {
            return (String) getInvocable().invokeMethod(_namespace,
                AsymmetricConstants.JS_ASYMMETRIC_SIGNING_FUNCTION,
                _privateKeyPem, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_NAMESPACE
                        + "."
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNING_FUNCTION
                        + " in resources file "
                        + AsymmetricConstants.JS_ASYMMETRIC_SIGNER_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not digitally sign data, using JavaScript.", e);
        }
    }

    private void verifySignatureUsingJava(final String signatureB64)
            throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Verifying digital signature, using Java...");

        putExceptionData("Signature (Base64 encoded) [JS]", signatureB64);

        try {
            boolean verified = _asymmetricService.verifySignature(
                Base64.getDecoder().decode(signatureB64), _publicKey,
                _data);

            if (!verified) {
                throw new GeneralCryptoLibException(
                    "Verification of digital signature (Base64 encoded) "
                        + signatureB64 + " was false.");
            }
        } catch (GeneralCryptoLibException e) {
            throw buildExceptionWithData(
                "Could not verify JavaScript generated signature, using Java.",
                e);
        }
    }
}
