/*
 * 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.commons.infrastructure.remote.service;

import javax.annotation.PostConstruct;

import com.scytl.products.ov.commons.beans.domain.model.certificate.CertificateEntity;
import com.scytl.products.ov.commons.infrastructure.exception.OvCommonsInfrastructureException;
import com.scytl.products.ov.commons.infrastructure.remote.client.CertificateServiceClient;
import com.scytl.products.ov.commons.infrastructure.remote.client.RestClientConnectionManager;
import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitConsumer;
import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitException;

import retrofit2.Retrofit;
/**
 * Service implementation for retrieving certificates that are not stored in a different deployment
 *  (meaning that they are accessible only by calling another microservice).
 */
public class RemoteCertificateServiceImpl implements RemoteCertificateService {

    public static final String CERTIFICATES_CONTEXT_URL_PROPERTY = "CERTIFICATES_CONTEXT_URL";

    private static final String URI_CERTIFICATE_REGISTRY = System.getProperty(CERTIFICATES_CONTEXT_URL_PROPERTY);

	private static final String PATH_CERTIFICATES = "certificates/public";

    private static final String PATH_TENANT_DATA = "tenantdata";

    private CertificateServiceClient certificateServiceClient;

    @PostConstruct
    public void intializeElectionInformationAdminClient() throws RetrofitException {

        Retrofit client;
        try {

            client = RestClientConnectionManager.getInstance().getRestClient(URI_CERTIFICATE_REGISTRY);

        } catch (OvCommonsInfrastructureException e) {
            throw new RetrofitException("Error occurred while trying to obtain a REST client.", e);
        }

        certificateServiceClient = client.create(CertificateServiceClient.class);
    }

    @Override
    public CertificateEntity getAdminBoardCertificate(String id) throws RetrofitException {
        
        return RetrofitConsumer.processResponse(certificateServiceClient.getAdminCertificate(PATH_CERTIFICATES, id));
        
    }

    @Override
    public CertificateEntity getTenantCACertificate(String tenantId) throws RetrofitException{
        return RetrofitConsumer.processResponse(certificateServiceClient.getTenantCACertificate(PATH_TENANT_DATA,tenantId));
    }

}
