/*
 * 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.ei.ui.ws.rs.application.operation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.List;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.primitives.primes.utils.PemUtils;
import com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;
import com.scytl.products.ov.commons.beans.domain.model.certificate.CertificateEntity;
import com.scytl.products.ov.commons.beans.exceptions.ApplicationException;
import com.scytl.products.ov.commons.beans.exceptions.ApplicationExceptionMessages;
import com.scytl.products.ov.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitException;
import com.scytl.products.ov.commons.infrastructure.remote.service.RemoteCertificateService;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import com.scytl.products.ov.commons.ui.Constants;
import com.scytl.products.ov.commons.ui.ws.rs.ErrorCodes;
import com.scytl.products.ov.commons.util.HttpRequestService;
import com.scytl.products.ov.commons.util.JsonUtils;
import com.scytl.products.ov.commons.verify.JSONVerifier;
import com.scytl.products.ov.ei.services.domain.model.ballot.Ballot;
import com.scytl.products.ov.ei.services.domain.model.ballot.BallotData;
import com.scytl.products.ov.ei.services.domain.model.ballot.BallotRepository;
import com.scytl.products.ov.ei.services.domain.model.ballot.BallotText;
import com.scytl.products.ov.ei.services.domain.model.ballot.BallotTextRepository;
import com.scytl.products.ov.ei.services.infrastructure.remote.EiRemoteCertificateService;

/**
 * Web service for handling ballot data resource.
 */
@Path("/ballotdata")
@Stateless
public class BallotDataResource {

    public static final String ADMINISTRATION_BOARD_CN_PREFIX = "AdministrationBoard ";

    public static final String JSON_ATTRIBUTE_NAME_SIGNED_OBJECT = "signedObject";

    // The name of the resource handle by this web service.
    private static final String RESOURCE_NAME = "ballotdata";

    // The name of the query parameter tenantId
    private static final String QUERY_PARAMETER_TENANT_ID = "tenantId";

    // The name of the query parameter electionEventId
    private static final String QUERY_PARAMETER_ELECTION_EVENT_ID = "electionEventId";

    // The name of the query parameter ballotId
    private static final String QUERY_PARAMETER_BALLOT_ID = "ballotId";

    // The name of the query parameter adminBoardId
    private static final String QUERY_PARAMETER_ADMIN_BOARD_ID = "adminBoardId";

    // An instance of the ballot repository
    @EJB
    private BallotRepository ballotRepository;

    // An instance of the ballot text repository
    @EJB
    private BallotTextRepository ballotTextRepository;

    private static final Logger LOG = LoggerFactory.getLogger(BallotDataResource.class);

    @Inject
    private TransactionInfoProvider transactionInfoProvider;

    @Inject
    private HttpRequestService httpRequestService;

    @Inject
    @EiRemoteCertificateService
    private RemoteCertificateService remoteCertificateService;

    @Inject
    private TrackIdInstance trackIdInstance;

    /**
     * Save data for a ballot given the tenant, the election event id and the ballot identifier.
     *
     * @param tenantId - the tenant identifier.
     * @param electionEventId - the election event identifier.
     * @param ballotId - the ballot identifier.
     * @param ballotData - the data for a ballot.
     * @param request - the http servlet request.
     * @return Returns status 200 on success.
     * @throws ApplicationException if the input parameters are not valid.
     */
    @POST
    @Path("tenant/{tenantId}/electionevent/{electionEventId}/ballot/{ballotId}/adminboard/{adminBoardId}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response saveBallotData(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) String trackingId,
                                   @PathParam(QUERY_PARAMETER_TENANT_ID) final String tenantId,
                                   @PathParam(QUERY_PARAMETER_ELECTION_EVENT_ID) final String electionEventId,
                                   @PathParam(QUERY_PARAMETER_BALLOT_ID) final String ballotId,
                                   @PathParam(QUERY_PARAMETER_ADMIN_BOARD_ID) final String adminBoardId,
                                   @NotNull final BallotData ballotData,
                                   @Context final HttpServletRequest request) throws ApplicationException {

        // set the track id to be logged
        trackIdInstance.setTrackId(trackingId);

        // transaction id generation
        transactionInfoProvider.generate(tenantId, httpRequestService.getIpClientAddress(request),
            httpRequestService.getIpServer(request));

        LOG.info("Saving ballot data for ballotId: {}, electionEventId: {}, and tenantId: {}.", ballotId, electionEventId,
            tenantId);

        LOG.info("Fetching the administration board certificate");
        final String adminBoardCommonName = ADMINISTRATION_BOARD_CN_PREFIX + adminBoardId;
        Certificate adminBoardCert = null;
        try {
	        final CertificateEntity adminBoardCertificateEntity =
	            remoteCertificateService.getAdminBoardCertificate(adminBoardCommonName);
	        final String adminBoardCertPEM = adminBoardCertificateEntity.getCertificateContent();
            adminBoardCert = PemUtils.certificateFromPem(adminBoardCertPEM);
        } catch (final GeneralCryptoLibException | RetrofitException e) {
            LOG.error("An error occurred while fetching the administration board certificate", e);
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        final PublicKey adminBoardPublicKey = adminBoardCert.getPublicKey();
        validateParameters(tenantId, electionEventId, ballotId);
        final JSONVerifier verifier = new JSONVerifier();

        try {
            final Ballot ballot = new Ballot();
            ballot.setBallotId(ballotId);
            ballot.setElectionEventId(electionEventId);
            ballot.setTenantId(tenantId);

            final String signedBallot = ballotData.getBallot();
            String stringBallot;
            try {
                LOG.info("Verifying ballot signature");
                stringBallot = verifier.verify(adminBoardPublicKey, signedBallot, String.class);
                LOG.info("Ballot signature was successfully verified");
            } catch (final Exception e) {
                LOG.error("Ballot signature could not be verified", e);
                return Response.status(Response.Status.PRECONDITION_FAILED).build();
            }
            ballot.setJson(stringBallot);
            ballot.setSignature(signedBallot);
            ballotRepository.save(ballot);

            final BallotText ballotText = new BallotText();
            ballotText.setBallotId(ballotId);
            ballotText.setElectionEventId(electionEventId);
            ballotText.setTenantId(tenantId);

            final String signedBallotTextsArray = ballotData.getBallottext();
            final JsonArray signedBallotTextsJsonArray = JsonUtils.getJsonArray(signedBallotTextsArray);

            final List<JsonObject> listBallotTexts = new ArrayList<>();

            boolean signaturesVerification = true;
            for (int i = 0; i < signedBallotTextsJsonArray.size(); i++) {

                final JsonObject ballotTextInArray = signedBallotTextsJsonArray.getJsonObject(i);
                final String ballotTextSignature = ballotTextInArray.getString(JSON_ATTRIBUTE_NAME_SIGNED_OBJECT);

                try {
                    LOG.info("Verifying ballot text signature");
                    final String stringBallotText = verifier.verify(adminBoardPublicKey, ballotTextSignature, String.class);
                    final JsonObject ballotTextJsonObject = JsonUtils.getJsonObject(stringBallotText);
                    listBallotTexts.add(ballotTextJsonObject);

                    LOG.info("Ballot text signature was successfully verified");
                } catch (final Exception e) {
                    signaturesVerification = false;
                    LOG.error("Ballot text signature could not be verified", e);
                    break;
                }
            }
            if (!signaturesVerification) {
                return Response.status(Response.Status.PRECONDITION_FAILED).build();
            }
            final JsonArray ballotTexts = JsonUtils.getJsonArray(listBallotTexts.toString());
            ballotText.setJson(ballotTexts.toString());
            ballotText.setSignature(signedBallotTextsJsonArray.toString());
            ballotTextRepository.save(ballotText);

            LOG.info("Ballot with ballotId: {}, electionEventId: {}, and tenantId: {} saved.", ballotId, electionEventId,
                tenantId);

        } catch (final DuplicateEntryException ex) {
            LOG.warn(
                "Duplicate entry tried to be inserted for ballot: {}, electionEventId: {}, and tenantId: {}.",
                ballotId, electionEventId, tenantId, ex);
        }

        return Response.ok().build();
    }

    // Validate parameters.
    private void validateParameters(final String tenantId, final String electionEventId, final String ballotId)
        throws ApplicationException {
        if (tenantId == null || tenantId.isEmpty())
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_TENANT_ID);

        if (electionEventId == null || electionEventId.isEmpty())
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_ELECTION_EVENT_ID);

        if (ballotId == null || ballotId.isEmpty())
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_BALLOT_ID);
    }
}
