package eu.dnetlib.common.profile;

import java.util.LinkedList;
import java.util.List;

import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.rmi.enabling.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author jochen
 * @deprecated this class is deprecated, use ResourceCache instead.
 */
@Deprecated
public class ResourceDaoRemoteSupport implements IResourceDaoSupport {

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

	@Autowired
	private UniqueServiceLocator serviceLocator;

	public List<Resource> getResources(String xquery) {
		List<Resource> list = new LinkedList<>();
		try {
			List<String> profileList = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(xquery);
			if (profileList != null) {
				for (String profile : profileList) {
					Resource resource = new Resource(profile);
					list.add(resource);
				}
			}
		} catch (ISLookUpException e) {
			log.error(e);
		} catch (DocumentException e) {
			log.error(e);
		}
		return list;
	}

	@Override
	public Resource getResourceByXquery(String xquery) {
		Resource resource = null;
		String profile;
		try {
			profile = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(xquery);
			resource = new Resource(profile);
		} catch (ISLookUpDocumentNotFoundException e) {
			log.error(e);
		} catch (ISLookUpException e) {
			log.error(e);
		} catch (DocumentException e) {
			log.error(e);
		}
		return resource;
	}

	public Resource getResource(String id) {
		Resource resource = null;
		String profile;
		try {
			profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(id);
			resource = new Resource(profile);
		} catch (ISLookUpDocumentNotFoundException e) {
			log.error(e);
		} catch (ISLookUpException e) {
			log.error(e);
		} catch (DocumentException e) {
			log.error(e);
		}
		return resource;
	}

	@Override
	public void removeResource(String id, Resource resource) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateResource(String id, Resource resource) {
		try {
			serviceLocator.getService(ISRegistryService.class).updateProfile(resource.getValue("//RESOURCE_IDENTIFIER/@value"), resource.getResource().asXML(),
					resource.getValue("//RESOURCE_TYPE/@value"));
		} catch (ISRegistryException e) {
			log.error(e);
			throw new IllegalStateException("cannot update profile.", e);
		}
	}

}
