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

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
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.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Optional;

import com.scytl.products.ov.kt.domain.model.ballotbox.BallotBoxTranslation;
import com.scytl.products.ov.kt.domain.model.ballotbox.BallotBoxTranslationList;
import com.scytl.products.ov.kt.services.BallotBoxTranslationService;

/**
 * Web service for creating and getting voting card translation.
 */
@Path(BallotBoxResource.RESOURCE_PATH)
@Stateless(name = "kt-BallotBoxResource")
public class BallotBoxResource {
	
	static final String RESOURCE_PATH = "/keytranslation/ballotbox";
	
	static final String GET_BALLOT_BOX_TRANSLATION_BY_ALIAS = "/tenant/{tenantId}/electionevent/{electionEventId}/alias/{alias}";

    static final String PARAMETER_VALUE_TENANT_ID = "tenantId";

    static final String PARAMETER_VALUE_ELECTION_EVENT_ID = "electionEventId";

    static final String PARAMETER_VALUE_ALIAS = "alias";

    private static final String PARAMETER_VALUE_BBID = "bbid";

    private static final Logger LOG = LoggerFactory.getLogger(BallotBoxResource.class);
    
    @Inject
    private BallotBoxTranslationService translationService;


    /**
     * Returns an object containing information about ballot box translation which matches with the provided parameters.
     *
     * @param tenantId - the tenant identifier.
     * @param electionEventId - the election event identifier.
     * @param alias - the ballot box alias identifier.
     * @return http status 200 with BallotBoxTranslation object in json format if resource is found. Otherwise, http
     *         status 404 if not found.
     * @throws IOException if there are errors during conversion of vote to json format.
     */
    @Path(GET_BALLOT_BOX_TRANSLATION_BY_ALIAS)
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBallotBoxTranslationByAlias(@NotNull @PathParam(PARAMETER_VALUE_TENANT_ID) String tenantId,
                                            @NotNull @PathParam(PARAMETER_VALUE_ELECTION_EVENT_ID) String electionEventId,
                                            @NotNull @PathParam(PARAMETER_VALUE_ALIAS) String alias) {

        final Optional<BallotBoxTranslation> translation = translationService.findByAlias(tenantId, electionEventId, alias);
        if (translation.isPresent()) {
            return Response.ok().entity(translation.get()).build();
        } else {
            return Response.status(Status.NOT_FOUND).build();
        }
    }

    /**
     * Returns an object containing information about ballot box translation which matches with the provided parameters.
     *
     * @param tenantId - the tenant identifier.
     * @param electionEventId - the election event identifier.
     * @param bbid - the ballot box identifier.
     * @return http status 200 with BallotBoxTranslation object in json format if resource is found. Otherwise, http
     *         status 404 if not found.
     * @throws IOException if there are errors during conversion of vote to json format.
     */
    @Path("/tenant/{tenantId}/electionevent/{electionEventId}/id/{bbid}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBallotBoxTranslationById(@NotNull @PathParam(PARAMETER_VALUE_TENANT_ID) String tenantId,
                                            @NotNull @PathParam(PARAMETER_VALUE_ELECTION_EVENT_ID) String electionEventId,
                                            @NotNull @PathParam(PARAMETER_VALUE_BBID) String bbid) {

        final Optional<BallotBoxTranslation> translation = translationService.findByBallotBoxId(tenantId, electionEventId, bbid);
        if (translation.isPresent()) {
            return Response.ok().entity(translation.get()).build();
        } else {
            return Response.status(Status.NOT_FOUND).build();
        }
    }

    /**
     * Stores ballot box translation information in the system.
     *
     * @param tenantId the tenant identifier.
     * @param translationsReader Reader for the translation json.
     * @return The http response of execute the operation. HTTP status code 200 if the request has succeed.
     */
    @Path("/secured/tenant/{tenantId}")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response uploadBallotBoxTranslation(@NotNull @PathParam(PARAMETER_VALUE_TENANT_ID) String tenantId,
                                                @NotNull BallotBoxTranslationList translations) {

        try {
            translationService.saveOrUpdate(tenantId, translations);
            return Response.ok().build();
        } catch (IllegalArgumentException iaE) {
        	LOG.error("Error trying to upload Ballot Box Translation.", iaE);
            return Response.status(Status.BAD_REQUEST).entity(iaE.getMessage()).build();
        }
    }

}
