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

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 com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;
import com.scytl.products.ov.commons.beans.domain.model.receipt.Receipt;
import com.scytl.products.ov.commons.beans.exceptions.ApplicationException;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import com.scytl.products.ov.commons.ui.Constants;
import com.scytl.products.ov.commons.util.HttpRequestService;
import com.scytl.products.ov.ei.services.domain.service.vote.VoteService;

@Stateless(name = "ei-ReceiptResource")
@Path("/receipts")
public class ReceiptResource {

    @Inject
    private TrackIdInstance trackIdInstance;

    @Inject
    private TransactionInfoProvider transactionInfoProvider;

    @Inject
    private HttpRequestService httpRequestService;

    @Inject
    private VoteService voteService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/tenant/{tenantId}/electionevent/{electionEventId}/votingcard/{votingCardId}")
    public Response getReceiptByVotingCardId(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) String trackingId,
            @PathParam(Constants.PARAMETER_VALUE_TENANT_ID) String tenantId,
            @PathParam(Constants.PARAMETER_VALUE_ELECTION_EVENT_ID) String electionEventId,
            @PathParam(Constants.PARAMETER_VALUE_VOTING_CARD_ID) String votingCardId,
            @Context HttpServletRequest request) throws ApplicationException, ResourceNotFoundException {

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

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

        Receipt voteReceipt = voteService.getVoteReceipt(tenantId, electionEventId, votingCardId);

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

}
