/*
 * 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.products.ov.mixnet.proofs.bg.shuffle;

import java.util.concurrent.ForkJoinTask;

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

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.cryptoapi.Ciphertext;
import com.scytl.products.ov.mixnet.commons.beans.proofs.MultiExponentiationBasicProofAnswer;
import com.scytl.products.ov.mixnet.commons.beans.proofs.MultiExponentiationBasicProofInitialMessage;
import com.scytl.products.ov.mixnet.commons.beans.proofs.MultiExponentiationReductionAnswer;
import com.scytl.products.ov.mixnet.commons.beans.proofs.MultiExponentiationReductionInitialMessage;
import com.scytl.products.ov.mixnet.commons.beans.proofs.ProductProofMessage;
import com.scytl.products.ov.mixnet.commons.beans.proofs.ShuffleProofSecondAnswer;
import com.scytl.products.ov.mixnet.commons.homomorphic.Randomness;
import com.scytl.products.ov.mixnet.commons.proofs.bg.commitments.CommitmentParams;
import com.scytl.products.ov.mixnet.commons.proofs.bg.config.ProofsGeneratorConfigurationParams;
import com.scytl.products.ov.mixnet.commons.tools.MultiExponentiation;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.ComputeAllE;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.MultiExponentiationProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.basic.BasicInitialMessageGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.basic.BasicProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.basic.ParallelBasicAnswerGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.basic.ParallelBasicProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.reduction.ParallelReductionProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.multiexp.reduction.ReductionProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.product.ParallelProductProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.product.ProductProofGenerator;
import com.scytl.products.ov.mixnet.proofs.bg.state.StateHarvester;

/**
 * Implements the parallel mode.
 */
public class ParallelSecondAnswerGenerator implements SecondAnswerGenerator {

    private static final Logger LOG = LoggerFactory.getLogger("std");

    private final ProofsGeneratorConfigurationParams config;

    private final ProductProofGenerator productProofGenerator;

    private final MultiExponentiationProofGenerator multiexpProofGenerator;

    public ParallelSecondAnswerGenerator(final ProofsGeneratorConfigurationParams config,
            final Randomness[] randomExponents, final Ciphertext[][] ciphertexts, final CommitmentParams comParams,
            final ComputeAllE computeAllE, final MultiExponentiation limMultiExpo, final int concurrencyLevel) {
        super();
        this.config = config;

        this.productProofGenerator = new ParallelProductProofGenerator(this.config.getMatrixDimensions(), comParams,
        		this.config.getZpGroupParams().getQ(), limMultiExpo);

        final BasicProofGenerator basicProofGenerator = new ParallelBasicProofGenerator(this.config, comParams,
            limMultiExpo, computeAllE, concurrencyLevel);

        this.multiexpProofGenerator = new MultiExponentiationProofGenerator(this.config, ciphertexts, randomExponents,
            //
            basicProofGenerator, //
            new ParallelReductionProofGenerator(config, comParams.getCommitmentLength(), basicProofGenerator, comParams,
                computeAllE, limMultiExpo, concurrencyLevel));
    }

    @Override
    public void generate(final StateHarvester harvester)
            throws GeneralCryptoLibException {

        LOG.info("Generating the product proof...");
        final ForkJoinTask<Void> productProofCalculation = ForkJoinTask.adapt(() -> {
            productProofGenerator.generate(harvester);
            return null;
        });
        productProofCalculation.fork();

        LOG.info("Generating the multi-exponentiation proof...");
        multiexpProofGenerator.generate(harvester);
        LOG.info("Multi-exponentiation has been generated successfully");

        if (productProofCalculation.tryUnfork()) {
            productProofCalculation.invoke();
        } else {
            productProofCalculation.join();
        }
        LOG.info("Product proof has been generated successfully");

        collectSecondAnswer(harvester);
    }

    private void collectSecondAnswer(final StateHarvester harvester) {

        final ProductProofMessage productProofMsg =
            harvester.offer(ProductProofGenerator.Produced.PRODUCT_PROOF_MSG, ProductProofMessage.class);

        ShuffleProofSecondAnswer thisAns;
        if (config.applyReduction()) {

            final MultiExponentiationReductionInitialMessage iniME =
                harvester.offer(ReductionProofGenerator.Produced.REDUCT_MULTIEXP_INIT_MSG,
                    MultiExponentiationReductionInitialMessage.class);

            final MultiExponentiationReductionAnswer ansME = harvester.offer(
                ReductionProofGenerator.Produced.REDUCT_MULTIEXP_ANSWER, MultiExponentiationReductionAnswer.class);

            thisAns = new ShuffleProofSecondAnswer(iniME, ansME, productProofMsg);

        } else {

            final MultiExponentiationBasicProofInitialMessage iniME =
                harvester.offer(BasicInitialMessageGenerator.Produced.BASIC_MULTIEXP_INIT_MSG,
                    MultiExponentiationBasicProofInitialMessage.class);

            final MultiExponentiationBasicProofAnswer ansME = harvester.offer(
                ParallelBasicAnswerGenerator.Produced.BASIC_MULTIEXP_ANSWER, MultiExponentiationBasicProofAnswer.class);

            thisAns = new ShuffleProofSecondAnswer(iniME, ansME, productProofMsg);
        }
        harvester.collect(Produced.SHUFFLE_SECOND_ANSWER, thisAns);
    }
}
