package eu.dnetlib.openaire.directindex.api;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.Resource;
import java.io.IOException;

public class IndexDSRetriever {

	private static final Log log = LogFactory.getLog(IndexDSRetriever.class);
	@Value(value = "${openaire.api.directindex.findSolrIndexUrl.xquery}")
	private ClassPathResource findSolrIndexUrl;

	@Value(value = "${openaire.api.directindex.findIndexDsInfo.xquery}")
	private ClassPathResource findIndexDsInfo;

	@Resource
	private UniqueServiceLocator serviceLocator;

	@Cacheable("indexDsInfo")
	public IndexDsInfo calculateCurrentIndexDsInfo() throws IOException, ISLookUpException {

		log.info("Not using cache");

		final String queryUrl = IOUtils.toString(findSolrIndexUrl.getInputStream());
		final String queryDs = IOUtils.toString(findIndexDsInfo.getInputStream());

		final ISLookUpService lu = serviceLocator.getService(ISLookUpService.class);
		final String indexBaseUrl = lu.getResourceProfileByQuery(queryUrl);

		final String idxDs = lu.getResourceProfileByQuery(queryDs);

		if (idxDs.isEmpty()) {
			throw new IllegalStateException(queryDs + "\n\nreturned no results, check IS profiles");
		}

		final String[] arr = idxDs.split("@@@");
		return new IndexDsInfo(indexBaseUrl, arr[0].trim(), arr[1].trim(), arr[2].trim());
	}

	@CacheEvict(value="indexDsInfo", allEntries = true)
	public void evictCache(){
		log.info("Evicting indexDsInfo cache");
	}
}