/*
 * 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.symmetric;

import java.util.Base64;

import javax.crypto.SecretKey;
import javax.script.ScriptException;

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

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.interoperation.js.commands.Command;
import com.scytl.cryptolib.interoperation.js.commands.CommandException;
import com.scytl.cryptolib.interoperation.js.constants.CommonConstants;
import com.scytl.cryptolib.interoperation.js.constants.SymmetricConstants;
import com.scytl.cryptolib.primitives.primes.utils.PrimitivesTestDataGenerator;
import com.scytl.cryptolib.primitives.securerandom.constants.SecureRandomConstants;
import com.scytl.cryptolib.symmetric.service.SymmetricService;
import com.scytl.cryptolib.test.tools.utils.CommonTestDataGenerator;

/**
 * Tests the Java-JavaScript interoperation for MAC applications.
 */
public class TestMac extends Command {

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

    private final Object _namespace;

    private final SymmetricService _symmetricService;

    private SecretKey _secretKey;

    private String _secretKeyB64;

    private byte[] _data;

    private String _dataB64;

    /**
     * Default constructor.
     *
     * @throws CommandException
     *             if the script engine cannot evaluate the MAC interoperation
     *             tests implemented in JavaScript.
     */
    public TestMac() throws CommandException {
        super(SymmetricConstants.JS_MAC_TEST_PATH);

        _namespace = _engine.get(SymmetricConstants.JS_MAC_TEST_NAMESPACE);

        clearExceptionData();

        try {
            _symmetricService = new SymmetricService();

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

    /**
     * Generates a MAC using Java, verifies the result using JavaScript,
     * generates the same MACs using JavaScript and verifies the result using
     * Java. If no exceptions are thrown and the same MAC is generated both
     * times, then the interoperation test for MAC applications was successful.
     *
     * @throws CommandException
     *             if a JavaScript method cannot be found, a cryptographic
     *             operation fails or a MAC cannot be verified.
     */
    @Override
    public void execute() throws CommandException {

        String macB64 = generateUsingJava();

        verifyUsingJavaScript(macB64);

        macB64 = generateUsingJavaScript();

        verifyUsingJava(macB64);

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

    private void generateInputData() throws GeneralCryptoLibException {

        _secretKey = _symmetricService.getSecretKeyForHmac();
        _secretKeyB64 =
            Base64.getEncoder().encodeToString(_secretKey.getEncoded());
        putExceptionData("Secret Key (Base64 encoded) [Java]",
            _secretKeyB64);

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

    private String generateUsingJava() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Generating MAC, using Java...");

        try {
            String macB64 = Base64.getEncoder().encodeToString(
                _symmetricService.getMac(_secretKey, _data));
            putExceptionData("MAC (Base64) [Java]", macB64);

            return macB64;
        } catch (GeneralCryptoLibException e) {
            throw buildExceptionWithData(
                "Could not generate MAC, using Java.", e);
        }
    }

    private void verifyUsingJavaScript(final String macB64)
            throws CommandException {

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

        try {
            getInvocable().invokeMethod(_namespace,
                SymmetricConstants.JS_MAC_VERIFICATION_FUNCTION, macB64,
                _secretKeyB64, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + SymmetricConstants.JS_MAC_TEST_NAMESPACE + "."
                        + SymmetricConstants.JS_MAC_VERIFICATION_FUNCTION
                        + " in resources file "
                        + SymmetricConstants.JS_MAC_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not verify MAC, using JavaScript.", e);
        }
    }

    private String generateUsingJavaScript() throws CommandException {

        LOGGER.info(CommonConstants.LOGGER_PROMPT
            + "Generating MAC, using JavaScript...");

        try {
            return (String) getInvocable().invokeMethod(_namespace,
                SymmetricConstants.JS_MAC_GENERATION_FUNCTION,
                _secretKeyB64, _dataB64);
        } catch (NoSuchMethodException e) {
            throw new CommandException.Builder()
                .addMessage(
                    "Attempt by script engine to call non-existent function "
                        + SymmetricConstants.JS_MAC_TEST_NAMESPACE + "."
                        + SymmetricConstants.JS_MAC_GENERATION_FUNCTION
                        + " in resources file "
                        + SymmetricConstants.JS_MAC_TEST_PATH)
                .addCause(e).build();
        } catch (ScriptException e) {
            throw buildExceptionWithData(
                "Could not generate MAC, using JavaScript.", e);
        }
    }

    private void verifyUsingJava(final String macB64)
            throws CommandException {

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

        putExceptionData("MAC (Base64 encoded) [JS]", macB64);

        try {
            boolean verified = _symmetricService.verifyMac(_secretKey,
                Base64.getDecoder().decode(macB64), _data);

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