/*
 * 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.oscore.logging.core.provider.TransactionInfoProvider;
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.ResourceNotFoundException;
import com.scytl.products.ov.commons.beans.validation.ValidationErrorType;
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.validation.ValidationError;
import com.scytl.products.ov.ei.services.domain.model.validation.ElectionValidationRequest;
import com.scytl.products.ov.ei.services.domain.service.ballotbox.BallotBoxService;
import com.scytl.products.ov.ei.services.domain.service.election.ElectionService;
import com.scytl.products.ov.ei.services.infrastructure.persistence.CleansingOutputsService;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
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 javax.ws.rs.core.StreamingOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.commons.lang.StringUtils.isEmpty;

@Path(CleansingOutputsResource.RESOURCE_NAME)
@Stateless
public class CleansingOutputsResource {

    static final String RESOURCE_NAME = "cleansingoutputs";

    static final String SUCCESSFUL_VOTES_PATH = "secured/tenant/{tenantId}/electionevent/{electionEventId}/ballotbox/{ballotBoxId}/successfulvotes";

    static final String FAILED_VOTES_PATH = "secured/tenant/{tenantId}/electionevent/{electionEventId}/ballotbox/{ballotBoxId}/failedvotes";

    private static final String QUERY_PARAMETER_TENANT_ID = "tenantId";

    private static final String QUERY_PARAMETER_ELECTION_EVENT_ID = "electionEventId";

    private static final String QUERY_PARAMETER_BALLOT_BOX_ID = "ballotBoxId";

    @Inject
    private TrackIdInstance trackIdInstance;

    @Inject
    private BallotBoxService ballotBoxService;

    @Inject
    private ElectionService electionService;

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

    @Inject
    private TransactionInfoProvider transactionInfoProvider;

    @Inject
    private HttpRequestService httpRequestService;

    @Inject
    private CleansingOutputsService cleansingOutputsService;

    /**
     * Return an stream of successful votes with its signature in case that
     * election is closed and the ballot box is not test.
     *
     * @param tenantId
     *            - the tenant identifier.
     * @param electionEventId
     *            - the election event identifier.
     * @param ballotBoxId
     *            - the ballot box identifier.
     * @return Returns the successful votes stream for the tenantId,
     *         electionEventId and ballotBoxId.
     * @throws ResourceNotFoundException
     *             if the related ballot box is not found.
     * @throws ApplicationException
     *             if the input parameters are not valid.
     */
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    @Path(SUCCESSFUL_VOTES_PATH)
    public Response getSuccessfulVotes(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) final String trackingId,
            @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,
            @Context final HttpServletRequest request) throws ApplicationException, ResourceNotFoundException {

        trackIdInstance.setTrackId(trackingId);

        transactionInfoProvider.generate(tenantId, httpRequestService.getIpClientAddress(request),
            httpRequestService.getIpServer(request));

        validateParameters(tenantId, electionEventId, ballotBoxId);

        boolean isTestBallotBox = ballotBoxService.checkIfTest(tenantId, electionEventId, ballotBoxId);

        if (!isTestBallotBox && electionIsOpen(tenantId, electionEventId, ballotBoxId)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }

        StreamingOutput entity =
            stream -> cleansingOutputsService.writeSuccessfulVotes(stream, tenantId, electionEventId, ballotBoxId);

        return Response.ok().entity(entity).header("Content-Disposition", "attachment; filename=successfulVotes.csv;")
            .build();
    }

    /**
     * Return an stream of failed votes with its signature in case that
     * election is closed.
     *
     * @param tenantId
     *            - the tenant identifier.
     * @param electionEventId
     *            - the election event identifier.
     * @param ballotBoxId
     *            - the ballot box identifier.
     * @return Returns the successful votes stream for the tenantId,
     *         electionEventId and ballotBoxId.
     * @throws ResourceNotFoundException
     *             if the related ballot box is not found.
     * @throws ApplicationException
     *             if the input parameters are not valid.
     */
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    @Path(FAILED_VOTES_PATH)
    public Response getFailedVotes(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) final String trackingId,
            @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,
            @Context final HttpServletRequest request) throws ApplicationException, ResourceNotFoundException {

        trackIdInstance.setTrackId(trackingId);

        transactionInfoProvider.generate(tenantId, httpRequestService.getIpClientAddress(request),
            httpRequestService.getIpServer(request));

        validateParameters(tenantId, electionEventId, ballotBoxId);

        boolean isTestBallotBox = ballotBoxService.checkIfTest(tenantId, electionEventId, ballotBoxId);

        if (!isTestBallotBox && electionIsOpen(tenantId, electionEventId, ballotBoxId)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }

        StreamingOutput entity =
            stream -> cleansingOutputsService.writeFailedVotes(stream, tenantId, electionEventId, ballotBoxId);

        return Response.ok().entity(entity).header("Content-Disposition", "attachment; filename=failedVotes.csv;")
            .build();
    }

    private void validateParameters(final String tenantId, final String electionEventId, final String ballotBoxId)
            throws ApplicationException {
        if (isEmpty(tenantId)) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_TENANT_ID);
        }
        if (isEmpty(electionEventId)) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_ELECTION_EVENT_ID);
        }
        if (isEmpty(ballotBoxId)) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_QUERY_PARAMETER_IS_NULL,
                RESOURCE_NAME, ErrorCodes.MISSING_QUERY_PARAMETER, QUERY_PARAMETER_BALLOT_BOX_ID);
        }
    }

    private boolean electionIsOpen(String tenantId, String electionEventId, String ballotBoxId) {
        ElectionValidationRequest electionValidationRequest =
            ElectionValidationRequest.create(tenantId, electionEventId, ballotBoxId, true);
        final ValidationError validationResult = electionService.validateIfElectionIsOpen(electionValidationRequest);
        if (!ValidationErrorType.ELECTION_OVER_DATE.equals(validationResult.getValidationErrorType())) {
            LOG.error("Ballot box {} not closed therefore cleansing outputs not available ", ballotBoxId);
            return true;
        }
        return false;
    }
}
