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

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.bean.ElGamalPrivateKey;
import com.scytl.cryptolib.elgamal.bean.ElGamalPublicKey;
import com.scytl.cryptolib.mathematical.groups.impl.Exponent;
import com.scytl.cryptolib.mathematical.groups.impl.ZpGroupElement;

public final class ElGamalHelper {
    private ElGamalHelper() {
    }

    public static final ElGamalPublicKey extractPublicKey(final ElGamalPrivateKey privateKey)
            throws GeneralCryptoLibException {
        List<Exponent> exponents = privateKey.getKeys();
        ZpGroupElement generator = privateKey.getGroup().getGenerator();
        List<ZpGroupElement> elements = new ArrayList<>(exponents.size());
        for (Exponent exponent : exponents) {
            ZpGroupElement element = generator.exponentiate(exponent);
            elements.add(element);
        }
        return new ElGamalPublicKey(elements, privateKey.getGroup());
    }

    public static byte[] concatValues(final List<ZpGroupElement> elements) {

        List<byte[]> byteList =
            elements.stream().map(element -> element.getValue().toByteArray()).collect(Collectors.toList());

        int length = 0;

        for (byte[] item : byteList) {
            length += item.length;
        }

        byte[] result = new byte[length];
        int begPos = 0;
        for (byte[] item : byteList) {
            System.arraycopy(item, 0, result, begPos, item.length);
            begPos += item.length;
        }

        return result;
    }
}
