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

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

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

    @Produces
    ElectionInformationClient electionInformationClient() {
        return createRestClient(URI_ELECTION_INFORMATION, ElectionInformationClient.class);
    }

    @Produces
    VoterMaterialClient voterMaterialClient() {
        return createRestClient(VOTER_MATERIAL_CONTEXT_URL, VoterMaterialClient.class);
    }

    private static <T> T createRestClient(String url, Class<T> clazz) {
        Retrofit client;
        try {
            client = RestClientConnectionManager.getInstance().getRestClient(url);
        } catch (OvCommonsInfrastructureException e) {
        	throw new RestClientException("The Rest client could not be created.", e);
        }
        return client.create(clazz);
    }
}
