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

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 java.io.IOException;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;
import com.scytl.products.ov.au.services.domain.model.authentication.CredentialInformation;
import com.scytl.products.ov.au.services.domain.model.authentication.CredentialInformationFactory;
import com.scytl.products.ov.au.services.domain.service.authenticationcontent.AuthenticationContentService;
import com.scytl.products.ov.commons.beans.domain.model.authentication.AuthenticationContent;
import com.scytl.products.ov.commons.beans.exceptions.ApplicationException;
import com.scytl.products.ov.commons.beans.exceptions.ApplicationExceptionMessages;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.beans.validation.CryptographicOperationException;
import com.scytl.products.ov.commons.random.RandomType;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import com.scytl.products.ov.commons.ui.Constants;
import com.scytl.products.ov.commons.ui.ws.rs.ObjectMappers;
import com.scytl.products.ov.commons.util.HttpRequestService;

/**
 * The end point for authentication information resource.
 */
@Path("/informations")
@Stateless
public class CredentialInformationResource {

    // The name of the parameter value tenant id.
    private static final String PARAMETER_VALUE_TENANT_ID = "tenantId";

    // The name of the parameter value credential card id.
    private static final String PARAMETER_VALUE_CREDENTIAL_ID = "credentialId";

    // The name of the parameter value election event id.
    private static final String PARAMETER_VALUE_ELECTION_EVENT_ID = "electionEventId";

    // The track id instance
    @Inject
    private TrackIdInstance trackIdInstance;

    // An instance of the credential information factory
    @Inject
    private CredentialInformationFactory credentialInformationFactory;

    // An instance of the authentication content service
    @Inject
    private AuthenticationContentService authenticationContentService;

    @Inject
    private TransactionInfoProvider transactionInfoProvider;

    @Inject
    private HttpRequestService httpRequestService;

    /**
     * Reads authentication information requested for the tenant identified by
     * tenantId, election event and voting card.
     *
     * @param tenantId
     *            - the identifier of the tenant.
     * @param electionEventId
     *            - the identifier of the election event.
     * @param credentialId
     *            - the identifier of the credential.
     * @param trackId
     *            - the track id to be used for logging purposes.
     * @param request
     *            - the http servlet request.
     * @return If the operation is successfully performed, returns a response
     *         with HTTP status code 200 and the authentication information in
     *         json format.
     * @throws ApplicationException
     *             if one of the input parameters is not valid.
     * @throws ResourceNotFoundException
     *             if there is no voter material found.
     * @throws GeneralCryptoLibException
     *             if length is out of the range for this generator.
     * @throws IOException
     *             if there are some error during conversion from object to json
     *             format.
     * @throws CryptographicOperationException
     *             if there is a cryptographic error during the credential
     *             generation
     */
    @GET
    @Path("/tenant/{tenantId}/electionevent/{electionEventId}/credential/{credentialId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAuthenticationInformation(@HeaderParam(Constants.PARAMETER_HEADER_X_REQUEST_ID) String trackingId,
                                                 @PathParam(PARAMETER_VALUE_TENANT_ID) String tenantId,
                                                 @PathParam(PARAMETER_VALUE_ELECTION_EVENT_ID) String electionEventId,
                                                 @PathParam(PARAMETER_VALUE_CREDENTIAL_ID) String credentialId,
                                                 @Context HttpServletRequest request)
        throws ApplicationException, ResourceNotFoundException, GeneralCryptoLibException, IOException,
        CryptographicOperationException {
        // set the track id to be logged
        trackIdInstance.setTrackId(trackingId);

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

        // in case something from the input is not valid, it throws an exception
        validateInput(tenantId, electionEventId, credentialId);

        RandomType randomType = RandomType.BYTES;

        // recover random length from authentication content
        AuthenticationContent authenticationContent =
            authenticationContentService.getAuthenticationContent(tenantId, electionEventId);

        // create new credential information
        CredentialInformation credentialInformation = credentialInformationFactory.buildCredentialInformation(tenantId,
            electionEventId, credentialId, randomType, authenticationContent.getChallengeLength());

        // returns the result of operation
        return Response.ok(ObjectMappers.toJson(credentialInformation)).build();
    }

    // Does a basic validation of the input. In case something is wrong, just
    // throws an exception.
    private void validateInput(String tenantId, String electionEventId, String credentialId)
        throws ApplicationException {
        if (tenantId == null || tenantId.isEmpty()) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_TENANT_ID_IS_NULL);
        }
        if (electionEventId == null || electionEventId.isEmpty()) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_ELECTION_EVENT_ID_IS_NULL);
        }
        if (credentialId == null || credentialId.isEmpty()) {
            throw new ApplicationException(ApplicationExceptionMessages.EXCEPTION_MESSAGE_CREDENTIAL_ID_IS_NULL);
        }
    }
}
