/*
 * 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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.bean.ElGamalPublicKey;

public final class ElgamalPublicKeyReader extends SerializedDataReader {

    /**
     * Reads an ElGamal public key from a file. 
     *
     * @param publicKeyFile
     *            the path of the file containing the ElGamal public key.
     * @return The reconstructed ElGamalPublicKey
     * @throws IOException
     * @throws GeneralCryptoLibException 
     */
    public static ElGamalPublicKey readPublicKeyFromStream(final InputStream publicKeyInput) throws IOException, GeneralCryptoLibException {
        validateInput(publicKeyInput);

        try ( InputStreamReader reader = new InputStreamReader(publicKeyInput);
                BufferedReader fileReader = new BufferedReader(reader)) {
            return ElGamalPublicKey.fromJson(readLineAndConfirmNotNull(fileReader));
        }

    }

    private static void validateInput(final InputStream inputStream) {

        if (inputStream == null) {
            throw new IllegalArgumentException("The received inputStream cannot be null");
        }
    }
}
