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

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.scytl.cryptolib.elgamal.cryptoapi.Ciphertext;
import com.scytl.cryptolib.mathematical.groups.impl.ZpGroupElement;

public class CiphertextSerializer extends JsonSerializer<Ciphertext> {

    private static final String DELIMITER_WITHIN_ELEMENTS = ";";

    private static final String DELIMITER_BETWEEN_ELEMENTS = ",";

    @Override
    public void serialize(Ciphertext value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        gen.writeStartObject();

        String gamma = getElementAsString(value.getGamma());
        gen.writeStringField("gamma", gamma);

        if (value.getPhis().isEmpty()) {

            String phis = getElementAsString(value.getPhis().get(0));
            gen.writeStringField("phis", phis);

        } else {

            String phis = getElementAsString(value.getPhis().get(0));

            for (int i = 1; i < value.getPhis().size(); i++) {

                phis += DELIMITER_BETWEEN_ELEMENTS;

                phis += getElementAsString(value.getPhis().get(i));
            }

            gen.writeStringField("phis", phis);
        }

        gen.writeEndObject();
    }

    private static String getElementAsString(ZpGroupElement element) {

        StringBuilder sb = new StringBuilder();
        sb.append(element.getValue().toString());
        sb.append(DELIMITER_WITHIN_ELEMENTS);
        sb.append(element.getP().toString());
        sb.append(DELIMITER_WITHIN_ELEMENTS);
        sb.append(element.getQ().toString());
        return sb.toString();
    }
}
