/*
 * 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 cipher applications.
 */
public class TestAsymmetricCipher extends Command {

    private static final Logger LOGGER =
        LoggerFactory.getLogger(TestAsymmetricCipher.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 cipher
     *             interoperation tests implemented in JavaScript.
     */
    public TestAsymmetricCipher() throws CommandException {
        super(AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_PATH);

        _namespace = _engine
            .get(AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_NAMESPACE);

        clearExceptionData();

        try {
            _asymmetricService = new AsymmetricService();

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

    /**
     * Asymmetrically encrypts some data using Java, decrypts the result using
     * JavaScript, encrypts the same data using JavaScript and decrypts the
     * result using Java. If no exceptions are thrown and the original data can
     * be retrieved, then the interoperation test for asymmetric cipher
     * applications was successful.
     *
     * @throws CommandException
     *             if a JavaScript method cannot be found, a cryptographic
     *             operation fails or a decryption operation yields data that
     *             does not correspond to the original data.
     */
    @Override
    public void execute() throws CommandException {

        String encryptedDataB64 = encryptUsingJava();

        decryptUsingJavaScript(encryptedDataB64);

        encryptedDataB64 = encryptUsingJavaScript();

        decryptUsingJava(encryptedDataB64);

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

    private void generateInputData() throws GeneralCryptoLibException {

        KeyPair keyPair = _asymmetricService.getKeyPairForEncryption();

        _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 encrypt (Base64 encoded) [Java]",
            _dataB64);
    }

    private String encryptUsingJava() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Asymmetrically encrypting data, using Java...");

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

    private void decryptUsingJavaScript(final String encryptedDataB64)
            throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Asymmetrically decrypting data, using JavaScript...");

        try {
            getInvocable().invokeMethod(_namespace,
                AsymmetricConstants.JS_ASYMMETRIC_DECRYPTION_FUNCTION,
                _privateKeyPem, encryptedDataB64, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_NAMESPACE
                        + "."
                        + AsymmetricConstants.JS_ASYMMETRIC_DECRYPTION_FUNCTION
                        + " in resources file "
                        + AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not asymmetrically encrypt data, using JavaScript.",
                e);
        }
    }

    private String encryptUsingJavaScript() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Asymmetrically encrypting data, using JavaScript...");

        try {
            return (String) getInvocable().invokeMethod(_namespace,
                AsymmetricConstants.JS_ASYMMETRIC_ENCRYPTION_FUNCTION,
                _publicKeyPem, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_NAMESPACE
                        + "."
                        + AsymmetricConstants.JS_ASYMMETRIC_ENCRYPTION_FUNCTION
                        + " in resources file "
                        + AsymmetricConstants.JS_ASYMMETRIC_CIPHER_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not asymmetrically encrypt data, using JavaScript.",
                e);
        }
    }

    private void decryptUsingJava(final String encryptedDataB64)
            throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Asymmetrically decrypting data, using Java...");

        putExceptionData("Encrypted data (Base64 encoded) [JS]",
            encryptedDataB64);

        try {
            byte[] decryptedData = _asymmetricService.decrypt(_privateKey,
                Base64.getDecoder().decode(encryptedDataB64));
            String decryptedDataB64 =
                Base64.getEncoder().encodeToString(decryptedData);
            putExceptionData("Decrypted data (Base64 encoded) [Java]",
                decryptedDataB64);

            if (!decryptedDataB64.equals(_dataB64)) {
                throw new GeneralCryptoLibException(
                    "Expected decrypted data (Base64 encoded): " + _dataB64
                        + " ; Found: " + decryptedDataB64);
            }
        } catch (GeneralCryptoLibException e) {
            throw buildExceptionWithData(
                "Could not asymmetrically decrypt JavaScript encrypted data, using Java.",
                e);
        }
    }
}
