package it.cnr.isti.driver.utils;

import java.util.LinkedHashSet;
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;

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() {
		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)";
		String[] reps = lookupLocator.getService().quickSearchProfile(query);

		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;
		
	}
}
