/*
 * 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.ea.services.infrastructure.remote;

import retrofit2.Retrofit;

import javax.enterprise.inject.Produces;

import com.scytl.products.ov.commons.infrastructure.exception.OvCommonsInfrastructureException;
import com.scytl.products.ov.commons.infrastructure.exception.RestClientException;
import com.scytl.products.ov.commons.infrastructure.remote.client.RestClientConnectionManager;
import com.scytl.products.ov.ea.services.infrastructure.remote.client.AuthenticationClient;
import com.scytl.products.ov.ea.services.infrastructure.remote.client.VoterMaterialServiceClient;

/**
 * "Producer" class that centralizes instantiation of all (retrofit) remote service client interfaces
 */
public class RemoteClientProducer {

    private static final String AUTHENTICATION_CONTEXT_URL = System.getProperty("AUTHENTICATION_CONTEXT_URL");
    private static final String VOTER_MATERIAL_CONTEXT_URL = System.getProperty("VOTER_MATERIAL_CONTEXT_URL");

    @Produces
    AuthenticationClient authenticationClient() {
        return createRestClient(AUTHENTICATION_CONTEXT_URL, AuthenticationClient.class);
    }

    @Produces
    VoterMaterialServiceClient voterMaterialServiceClient() {
        return createRestClient(VOTER_MATERIAL_CONTEXT_URL, VoterMaterialServiceClient.class);
    }

    private static <T> T createRestClient(String url, Class<T> clazz) {
    	Retrofit client;
        try {
            client = RestClientConnectionManager.getInstance().getRestClient(url);
        } catch (OvCommonsInfrastructureException ociE) {
            throw new RestClientException("Error trying to obtain a REST client.", ociE);
        }
        return client.create(clazz);
    }
}
