package eu.dnetlib.openaire.dsm.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import eu.dnetlib.DnetOpenaireExporterProperties;
import eu.dnetlib.openaire.exporter.exceptions.DsmApiException;
import eu.dnetlib.openaire.exporter.model.vocabularies.Vocabulary;

/**
 * Created by claudio on 15/09/2017.
 */
@Component
public class VocabularyClientImpl implements VocabularyClient {

	private static final Log log = LogFactory.getLog(VocabularyClientImpl.class);

	@Autowired
	private DnetOpenaireExporterProperties config;

	@Override
	@Cacheable("vocabularies-cache")
	public Vocabulary getCountries() throws DsmApiException {
		return _getVocabulary(config.getVocabularies().getCountriesEndpoint(), Vocabulary.class);
	}

	@Override
	@Cacheable("vocabularies-cache")
	public Vocabulary getDatasourceTypologies() throws DsmApiException {
		return _getVocabulary(config.getVocabularies().getDatasourceTypologiesEndpoint(), Vocabulary.class);
	}

	private <T> T _getVocabulary(final String endpoint, final Class<T> clazz) throws DsmApiException {
		final RestTemplate rt = new RestTemplate();
		log.info("get vocabulary from " + endpoint);
		final ResponseEntity<T> rsp = rt.getForEntity(endpoint, clazz);

		if (!rsp.getStatusCode().is2xxSuccessful()) { throw new DsmApiException(rsp.getStatusCodeValue(), "unable to read content from " + endpoint); }

		return rsp.getBody();
	}

	@Override
	@CacheEvict(cacheNames = "vocabularies-cache", allEntries = true)
	@Scheduled(fixedDelayString = "${openaire.exporter.cache.ttl}")
	public void dropCache() {
		log.debug("dropped dsManager vocabulary cache");
	}

}
