/*
 * 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
 */
/**
 * Created by riglesias on 11/03/15.
 */
package com.scytl.products.ov.ag.ui.ws.rs.operation.voting;

import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitException;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.scytl.products.ov.ag.services.infrastructure.remote.voting.VotingWorkflowVotingClient;
import com.scytl.products.ov.ag.ui.ws.rs.RestApplication;
import com.scytl.products.ov.ag.ui.ws.rs.proxy.XForwardedForFactory;
import com.scytl.products.ov.ag.ui.ws.rs.proxy.XForwardedForFactoryImpl;
import com.scytl.products.ov.commons.infrastructure.remote.client.InputStreamTypedOutput;
import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitConsumer;
import com.scytl.products.ov.commons.tracking.TrackIdGenerator;
import com.scytl.products.ov.commons.util.PropertiesFileReader;

/**
 * Web service which will handle the process of voting and storing a ballot. For now this class is implemented only for
 * testing purposes.
 */
@Stateless(name = "ag-VoteResource")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Path(VoteResource.RESOURCE_PATH)
public class VoteResource {

    static final String VALIDATE_VOTE_AND_STORE = "/vote";

    static final String RESOURCE_PATH = RestApplication.API_OV_VOTING_BASEURI;

    // The properties file reader.
    private static final PropertiesFileReader PROPERTIES = PropertiesFileReader.getInstance();

    // The path to the resource authentication information.
    static final String VOTE_PATH = PROPERTIES.getPropertyValue("VOTE_PATH");

    private final XForwardedForFactory xForwardedForFactory = XForwardedForFactoryImpl.getInstance();

    private VotingWorkflowVotingClient votingWorkflowVotingClient;

    private TrackIdGenerator trackIdGenerator;
    
    private static final Logger LOG = LoggerFactory.getLogger(ReceiptResource.class);

    @Inject
	VoteResource(VotingWorkflowVotingClient votingWorkflowVotingClient, TrackIdGenerator trackIdGenerator) {
		this.votingWorkflowVotingClient = votingWorkflowVotingClient;
		this.trackIdGenerator = trackIdGenerator;
	}

    @Path(VALIDATE_VOTE_AND_STORE)
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response validateVoteAndStore(@PathParam(RestApplication.PARAMETER_VALUE_VERSION) final String version,
            @PathParam(RestApplication.PARAMETER_VALUE_TENANT_ID) final String tenantId,
            @PathParam(RestApplication.PARAMETER_VALUE_ELECTION_EVENT_ID) final String electionEventId,
            @PathParam(RestApplication.PARAMETER_VALUE_VOTING_CARD_ID) final String votingCardId,
            @NotNull @HeaderParam(RestApplication.PARAMETER_AUTHENTICATION_TOKEN) final String authenticationTokenJsonString,
            @NotNull final InputStream vote,
            @Context final HttpServletRequest request) {
        String xForwardedFor = xForwardedForFactory.newXForwardedFor(request);
        String trackingId = trackIdGenerator.generate();

        RequestBody body = new InputStreamTypedOutput(MediaType.APPLICATION_JSON, vote);

        try {
        	JsonObject processResponse = RetrofitConsumer.processResponse(
        			votingWorkflowVotingClient.validateVoteAndStore(VOTE_PATH, tenantId, electionEventId,
        		            votingCardId, authenticationTokenJsonString, xForwardedFor, trackingId, body));
	        return Response.ok().entity(processResponse.toString()).build();
    	} catch (RetrofitException rfE) {
			LOG.error("Error trying to validate vote and store.", rfE);
			return Response.status(rfE.getHttpCode()).build();
		}
    }
}
