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

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.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
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.admin.VoteVerificationAdminClient;
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;

/**
 * Web service for handling electoral data resource.
 */
@Stateless(name = "ag-vv-ElectoralDataResource")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Path(ElectoralDataVVResource.RESOURCE_PATH)
public class ElectoralDataVVResource {

    static final String SAVE_ELECTORAL_DATA =
        "tenant/{tenantId}/electionevent/{electionEventId}/electoralauthority/{electoralAuthorityId}/adminboard/{adminBoardId}";

    static final String RESOURCE_PATH = "/vv/electoraldata";

    // 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 verificationCardSetId
    private static final String QUERY_PARAMETER_ELECTORAL_AUTHORITY_ID = "electoralAuthorityId";

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

    // The path to the resource electoral data.
    static final String ELECTORAL_DATA_PATH = PROPERTIES.getPropertyValue("ELECTORAL_DATA_PATH");

    private static final String QUERY_PARAMETER_ADMIN_BOARD_ID = "adminBoardId";

    private final XForwardedForFactory xForwardedForFactory = XForwardedForFactoryImpl.getInstance();

    private VoteVerificationAdminClient voteVerificationAdminClient;

    private TrackIdGenerator trackIdGenerator;

    private static final Logger LOG = LoggerFactory.getLogger(ElectoralDataVVResource.class);
    
    @Inject
    ElectoralDataVVResource(VoteVerificationAdminClient voteVerificationAdminClient,
                            TrackIdGenerator trackIdGenerator) {
        this.voteVerificationAdminClient = voteVerificationAdminClient;
        this.trackIdGenerator = trackIdGenerator;
    }

    @POST
    @Path(SAVE_ELECTORAL_DATA)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response saveElectoralData(@PathParam(QUERY_PARAMETER_TENANT_ID) final String tenantId,
            @PathParam(QUERY_PARAMETER_ELECTION_EVENT_ID) final String electionEventId,
            @PathParam(QUERY_PARAMETER_ELECTORAL_AUTHORITY_ID) final String electoralAuthorityId,
            @PathParam(QUERY_PARAMETER_ADMIN_BOARD_ID) final String adminBoardId,
            @NotNull final InputStream data,
            @Context final HttpServletRequest request) {
        String xForwardedFor = xForwardedForFactory.newXForwardedFor(request);
        String trackingId = trackIdGenerator.generate();

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

        try (ResponseBody responseBody = RetrofitConsumer.processResponse(
        			voteVerificationAdminClient.saveElectoralData(ELECTORAL_DATA_PATH, tenantId,
        		            electionEventId, electoralAuthorityId, adminBoardId, xForwardedFor, trackingId, body))) {
	        return Response.ok().build();
        } catch (RetrofitException rfE) {
			LOG.error("Error trying to save electoral data.", rfE);
			return Response.status(rfE.getHttpCode()).build();
		}
    }
}
