/*
 * 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
 */
/**
 * $Id$
 *
 * @author riglesias
 * @date 7/11/16
 *
 *
 * All rights reserved.
 */
package com.scytl.products.ov.ea.domain.repository.authenticationtoken;

import com.google.gson.Gson;
import com.scytl.products.ov.commons.beans.domain.model.authentication.AuthenticationToken;
import com.scytl.products.ov.commons.beans.exceptions.AuthTokenRepositoryException;
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.TrackIdInstance;
import com.scytl.products.ov.commons.validation.ValidationResult;
import com.scytl.products.ov.ea.domain.model.extendedauthentication.validation.AuthenticationTokenService;

import javax.ejb.Stateless;
import javax.inject.Inject;

import com.scytl.products.ov.ea.services.infrastructure.remote.client.AuthenticationClient;

/**
 * Implementation of the service. All the things regarding token validations will
 * be redirected to the Context responsible of such operations. Thus, the authentication
 * context will perform any operation regarding auth token validations.
 */
@Stateless
public class AuthenticationTokenRepository implements AuthenticationTokenService{

    // The path to the resource for validate the authentication token.
    private static final String VALIDATION_AUTHENTICATION_TOKEN_PATH = "validations";

    private AuthenticationClient authenticationClient;

    @Inject
    private TrackIdInstance trackId;

    @Inject
    AuthenticationTokenRepository(AuthenticationClient authenticationClient) {
        this.authenticationClient = authenticationClient;
    }

    @Override
    public ValidationResult validateToken(String tenantId, String electionEventId, AuthenticationToken token) throws AuthTokenRepositoryException{

        final String votingCardId = token.getVoterInformation().getVotingCardId();
        Gson gson = new Gson();
        final String authTokenAsString = gson.toJson(token, AuthenticationToken.class);
        try {
			return RetrofitConsumer.processResponse(authenticationClient.validateAuthenticationToken(VALIDATION_AUTHENTICATION_TOKEN_PATH, tenantId, electionEventId, votingCardId, trackId.getTrackId(), authTokenAsString));
		} catch (RetrofitException rfE) {
			throw new AuthTokenRepositoryException("Error trying to validate token.", rfE);
		}
    }
}
