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


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 retrofit2.Retrofit;

/**
 * "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 AUTHENTICATION_CONTEXT_URL = System.getProperty("AUTHENTICATION_CONTEXT_URL");
    private static final String KEY_TRANSLATION_CONTEXT_URL = System.getProperty("KEY_TRANSLATION_CONTEXT_URL");
    private static final String VERIFICATION_CONTEXT_URL = System.getProperty("VERIFICATION_CONTEXT_URL");
    private static final String VERIFICATION_CODE_CONTEXT_URL = System.getProperty("VERIFICATION_CODE_CONTEXT_URL");

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

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

    @Produces
    KeyTranslationClient keyTranslationClient() {
        return createRestClient(KEY_TRANSLATION_CONTEXT_URL, KeyTranslationClient.class);
    }

    @Produces
    VerificationClient verificationClient() {
        return createRestClient(VERIFICATION_CONTEXT_URL, VerificationClient.class);
    }

    @Produces
    VerificationCodeClient verificationCodeClient() {
        return createRestClient(VERIFICATION_CODE_CONTEXT_URL, VerificationCodeClient.class);
    }


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