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

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;

import org.apache.commons.io.IOUtils;

import com.scytl.cryptolib.api.exceptions.CryptoLibException;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.mathematical.groups.impl.ZpSubgroup;

public class ZpGroupReader {

	/**
     * Non-public constructor
     */
	private ZpGroupReader() {
    }

    public static ZpSubgroup build(final InputStream encryptionParameters) throws IOException {

        try {
            String zpGroupJson = null;
            try (InputStream inputStream = encryptionParameters) {
                zpGroupJson = IOUtils.toString(inputStream);
            }

            return ZpSubgroup.fromJson(zpGroupJson);

        } catch (GeneralCryptoLibException e) {
            throw new CryptoLibException("Exception while deserializing group information", e);
        }
    }

    public static void serializeToStream(final ZpSubgroup zpGroup,
            final OutputStream output)
            throws GeneralCryptoLibException, IOException {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
            writer.println(zpGroup.toJson());
        }
    }

    public static ZpSubgroup createZpGroupFromParameterStrings(final String pAsString, final String qAsString,
            final String gAsString) {

        final BigInteger pAsBigInteger = new BigInteger(pAsString);
        final BigInteger qAsBigInteger = new BigInteger(qAsString);
        final BigInteger gAsBigInteger = new BigInteger(gAsString);

        try {

            return new ZpSubgroup(gAsBigInteger, pAsBigInteger, qAsBigInteger);

        } catch (GeneralCryptoLibException e) {
            throw new CryptoLibException(e);
        }
    }
}
