/*
 * 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 com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxStatus;
import com.scytl.products.ov.ei.services.infrastructure.remote.EiRemoteCertificateService;

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

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.security.PublicKey;
import java.security.cert.Certificate;

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.BallotBox;
import com.scytl.products.ov.commons.beans.BallotBoxContextData;
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.beans.exceptions.ResourceNotFoundException;
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.ui.ws.rs.ObjectMappers;
import com.scytl.products.ov.commons.util.HttpRequestService;
import com.scytl.products.ov.commons.verify.JSONVerifier;
import com.scytl.products.ov.ei.services.domain.common.SignedObject;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxContent;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxContentRepository;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxData;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxInformation;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxInformationRepository;

/**
 * Web service for handling ballot box data information.
 */
@Path("/ballotboxdata")
@Stateless
public class BallotBoxDataResource {

    public static final String ADMINISTRATION_BOARD_CN_PREFIX = "AdministrationBoard ";

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

    // 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 ballotBoxId
    private static final String QUERY_PARAMETER_BALLOT_BOX_ID = "ballotBoxId";

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

    @EJB
    private BallotBoxContentRepository ballotBoxContentRepository;

    @EJB
    private BallotBoxInformationRepository ballotBoxInformationRepository;

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

    @Inject
    private TransactionInfoProvider transactionInfoProvider;

    @Inject
    private HttpRequestService httpRequestService;

    @Inject
    @EiRemoteCertificateService
    private RemoteCertificateService remoteCertificateService;

    @Inject
    private TrackIdInstance trackIdInstance;

    /**
     * Adds ballot box "content" and "information" to the ballot box
     *
     * @param trackingId      - the track id to be used for logging purposes.
     * @param jsonContent     - the data to be added to a ballot box.
     * @param tenantId        - the tenant identifier.
     * @param electionEventId - the election event identifier.
     * @param ballotBoxId     - the ballot identifier.
     * @param request         - the http servlet request.
     * @return http status
     * @throws ApplicationException      if the input parameters are not valid.
     * @throws IOException               if there are errors during conversion of ballot to json format.
     * @throws ResourceNotFoundException if the ballot is not found.
     */
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("tenant/{tenantId}/electionevent/{electionEventId}/ballotbox/{ballotBoxId}/adminboard/{adminBoardId}")
    public Response addBallotBoxContentAndInformation(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) String trackingId,
                                                      @NotNull final BallotBoxData jsonContent,
                                                      @PathParam(QUERY_PARAMETER_TENANT_ID) final String tenantId,
                                                      @PathParam(QUERY_PARAMETER_ELECTION_EVENT_ID) final String electionEventId,
                                                      @PathParam(QUERY_PARAMETER_BALLOT_BOX_ID) final String ballotBoxId,
                                                      @PathParam(QUERY_PARAMETER_ADMIN_BOARD_ID) final String adminBoardId,
                                                      @Context final HttpServletRequest request)
        throws ApplicationException, IOException {

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

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

        // validate parameters
        validateParameters(tenantId, electionEventId, ballotBoxId);

        LOG.info("Adding ballot box content for ballotBoxId: {}, electionEventId: {}, and tenantId: {}.", ballotBoxId,
            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();


        final BallotBoxInformation ballotBoxInformation = new BallotBoxInformation();
        ballotBoxInformation.setTenantId(tenantId);
        ballotBoxInformation.setBallotBoxId(ballotBoxId);
        ballotBoxInformation.setElectionEventId(electionEventId);

        final String signedBallotBox = jsonContent.getBallotBox();
        final SignedObject signedBallotBoxObject = ObjectMappers.fromJson(signedBallotBox, SignedObject.class);
        final String signatureBallotBox = signedBallotBoxObject.getSignature();

        final JSONVerifier verifier = new JSONVerifier();
        BallotBox ballotBox = null;
        try {
            LOG.info("Verifying ballot box signature");
            ballotBox = verifier.verify(adminBoardPublicKey, signatureBallotBox, BallotBox.class);
            LOG.info("Ballot box signature was successfully verified");
        } catch (final Exception e) {
            LOG.error("Ballot box signature could not be verified", e);
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }

        try {
            final String ballotBoxJSON = ObjectMappers.toJson(ballotBox);
            ballotBoxInformation.setJson(ballotBoxJSON);
            ballotBoxInformation.setSignature(signatureBallotBox);
            ballotBoxInformation.setStatus(BallotBoxStatus.NONE);
            ballotBoxInformationRepository.save(ballotBoxInformation);

            final BallotBoxContent ballotBoxContent = new BallotBoxContent();
            ballotBoxContent.setTenantId(tenantId);
            ballotBoxContent.setElectionEventId(electionEventId);
            ballotBoxContent.setBallotBoxId(ballotBoxId);

            final String signedBallotBoxContents = jsonContent.getBallotBoxContextData();
            final SignedObject signedBallotBoxContentsObject = ObjectMappers.fromJson(signedBallotBoxContents, SignedObject.class);
            final String signatureBallotBoxContents = signedBallotBoxContentsObject.getSignature();

            BallotBoxContextData ballotBoxContents;
            try {
                LOG.info("Verifying ballot context data signature");
                ballotBoxContents =
                    verifier.verify(adminBoardPublicKey, signatureBallotBoxContents, BallotBoxContextData.class);
                LOG.info("Ballot context data signature was successfully verified");
            } catch (final Exception e) {
                LOG.error("Ballot context data signature could not be verified", e);
                return Response.status(Response.Status.PRECONDITION_FAILED).build();
            }
            final String ballotBoxContentsJSON = ObjectMappers.toJson(ballotBoxContents);
            ballotBoxContent.setJson(ballotBoxContentsJSON);
            ballotBoxContentRepository.save(ballotBoxContent);

            LOG.info("Ballot box content for ballotBoxId: {}, electionEventId: {}, and tenantId: {} added.", ballotBoxId,
                electionEventId, tenantId);
        } catch (final DuplicateEntryException ex) {
            LOG.warn("Duplicate entry tried to be inserted for ballot box: {}, electionEventId: {}, and tenantId: {}", ballotBoxId,
                electionEventId, tenantId, ex);
        }

        return Response.ok().build();

    }

    private void validateParameters(final String tenantId, final String electionEventId, final String ballotBoxId)
        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 (ballotBoxId == null || ballotBoxId.isEmpty())
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_BALLOT_BOX_ID);
    }
}
