package eu.dnetlib.functionality.lightui.utils;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;

public class CountryDriverCollection extends DynamicDriverCollection implements BeanFactoryAware {
	public static Log log = LogFactory.getLog(CountryDriverCollection.class);

	private String country;
	private BeanFactory beanFactory;

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public Set<Repository> getRepositories() throws ISLookUpException {
		Set<Repository> repositories = new LinkedHashSet<Repository>();

		String query = "for $x in collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')"
			+ "//CONFIGURATION[COUNTRY='" + getCountry() + "']"
			+ "return concat($x/OFFICIAL_NAME/text(),':-:', $x/ICON_URI,':-:',$x/REPOSITORY_WEBPAGE)";
		List<String> reps = lookupLocator.getService().quickSearchProfile(query);

		if (reps == null)
			reps = new ArrayList<String>();

		for (String repositoryTuple : reps) {
			String[] tuple = repositoryTuple.split(":-:");
			Repository rep = (Repository) beanFactory.getBean("repositoryImpl", tuple);
			repositories.add(rep);
		}

		return repositories;
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;

	}

}
