package eu.dnetlib.datasource.publisher.clients;

import eu.dnetlib.datasource.publisher.ApiException;
import eu.dnetlib.datasource.publisher.clients.utils.IndexDsInfo;
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.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;

/**
 * Created by claudio on 20/10/2016.
 */
public class ISLookupClient {

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

	@Autowired
	private UniqueServiceLocator serviceLocator;

	@Value(value = "${datasource.publisher.findSolrIndexUrl.xquery}")
	private ClassPathResource findSolrIndexUrl;

	@Value(value = "${datasource.publisher.findIndexDsInfo.xquery}")
	private ClassPathResource findIndexDsInfo;

	@Cacheable("datasources-is-cache")
	public IndexDsInfo calculateCurrentIndexDsInfo() throws ApiException {
		log.warn("calculateCurrentIndexDsInfo(): not using cache");
		try {
			final String queryUrl = IOUtils.toString(findSolrIndexUrl.getInputStream());
			final String queryDs = IOUtils.toString(findIndexDsInfo.getInputStream());

			final ISLookUpService lookUpService = serviceLocator.getService(ISLookUpService.class);
			final String indexBaseUrl = lookUpService.getResourceProfileByQuery(queryUrl);
			final String[] arr = lookUpService.getResourceProfileByQuery(queryDs).split("@@@");

			return new IndexDsInfo(indexBaseUrl, arr[0].trim(), arr[1].trim(), arr[2].trim());
		} catch (Exception e) {
			throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Error querying information system");
		}
	}

	public String getLastIndexingDate(final IndexDsInfo info) throws ApiException {
		final String xquery = String.format("for $x in collection('')/RESOURCE_PROFILE[./HEADER/RESOURCE_TYPE/@value = 'IndexDSResourceType' and "
				+ "./BODY/CONFIGURATION/METADATA_FORMAT = '%s']\n"
				+ "return $x/BODY/STATUS/INDEX_LAST_UPDATE/text()", info.getFormat());
		try {
			final ISLookUpService lookUpService = serviceLocator.getService(ISLookUpService.class);
			return lookUpService.getResourceProfileByQuery(xquery);
		} catch (ISLookUpException e) {
			throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Error querying index DS profile: " + info.getFormat());
		}
	}

}
