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

import com.google.gson.JsonObject;
import okhttp3.RequestBody;

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.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

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.infrastructure.remote.client.RetrofitException;
import com.scytl.products.ov.commons.tracking.TrackIdGenerator;
import com.scytl.products.ov.commons.util.PropertiesFileReader;

/**
 * The end point for the Authentication Tokens.
 */
@Stateless(name = "ag-AuthenticationTokenResource")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Path(AuthenticationTokenResource.RESOURCE_PATH)
public class AuthenticationTokenResource {

    static final String RESOURCE_PATH = RestApplication.API_OV_VOTING_BASEURI_AUTH + "/auth" + "/authenticate-token";

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

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

    private final XForwardedForFactory xForwardedForFactory = XForwardedForFactoryImpl.getInstance();

    private VotingWorkflowVotingClient votingWorkflowVotingClient;

    private TrackIdGenerator trackIdGenerator;

    private static final Logger LOG = LoggerFactory.getLogger(AuthenticationTokenResource.class);
    
    @Inject
    AuthenticationTokenResource(VotingWorkflowVotingClient votingWorkflowVotingClient,
                                TrackIdGenerator trackIdGenerator) {
        this.votingWorkflowVotingClient = votingWorkflowVotingClient;
        this.trackIdGenerator = trackIdGenerator;
    }

    @POST
    @Path("")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getAuthenticationToken(@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_CREDENTIAL_ID) final String credentialId,
            @NotNull final InputStream challengeInformation, @Context final HttpServletRequest request) {
        String xForwardedFor = xForwardedForFactory.newXForwardedFor(request);
        String trackingId = trackIdGenerator.generate();

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

        try {
        	JsonObject processResponse = RetrofitConsumer.processResponse(
        			votingWorkflowVotingClient.getAuthenticationToken(AUTHENTICATION_TOKEN_PATH, tenantId,
        		            electionEventId, credentialId, xForwardedFor, trackingId, body));
	        return Response.ok().entity(processResponse.toString()).build();
        } catch (RetrofitException rfE) {
     		LOG.error("Error trying to get authentication token.", rfE);
			return Response.status(rfE.getHttpCode()).build();
		}
    }
}
