/*
 * 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.proofs.bg.commitments;

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

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import com.scytl.cryptolib.mathematical.groups.impl.ZpGroupElement;
import com.scytl.cryptolib.mathematical.groups.impl.ZpSubgroup;
import com.scytl.products.ov.mixnet.commons.tools.GroupTools;

/**
 * This class encapsulates a set of commitment parameters, which are needed to generate {@link PrivateCommitment}.
 */
public class CommitmentParams {

    private final ZpGroupElement h;

    private final ZpGroupElement[] g;

    private final ZpSubgroup group;

    private final int commitmentlength;

    public CommitmentParams(final ZpSubgroup group, final int n) {
        this.group = group;
        this.h = GroupTools.getRandomElement(group);
        this.commitmentlength = n;
        this.g = GroupTools.getVectorRandomElement(group, this.commitmentlength);
    }

    public CommitmentParams(final ZpSubgroup group, final ZpGroupElement h, final ZpGroupElement[] g) {
    	this.group = group;
    	this.h = h;
    	this.g = g;
    	this.commitmentlength = this.g.length;
    }

    public ZpGroupElement getH() {
        return h;
    }

    public ZpGroupElement[] getG() {
        return g;
    }

    public ZpSubgroup getGroup() {
        return group;
    }

    public int getCommitmentLength() {
        return commitmentlength;
    }

    /**
     * Serializes the values of this CommitmentParams to a stream.
     * <p>
     * The generated file will contain the following data (each value is on a separate line):
     * <ul>
     * <li>Group p parameter
     * <li>Group q parameter
     * <li>Group g parameter
     * <li>H
     * <li>G[0]
     * <li>G[i]
     * <li>...
     * <li>G[n]
     * </ul>
     * <p>
     * Note: There is a variable number of G elements.
     *
     * @param output
     *            the stream
     * @throws IOException failed to write the parameters.
     */
    public void serializeToStream(final OutputStream output) throws IOException {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
            // write the group information
            writer.println(group.getP().toString());
            writer.println(group.getQ().toString());
            writer.println(group.getGenerator().getValue().toString());
            
            // write the element information
            writer.println(h.getValue().toString());
            for (ZpGroupElement a_g : g) {
                writer.println(a_g.getValue().toString());
            }
        }
    }
}
