package eu.dnetlib.functionality.modular.ui.is.bulk;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;

import com.google.common.collect.Maps;

import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.is.store.rmi.ISStoreService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.tools.StreamOpaqueResource;

public class ProfileImporter implements ResourceLoaderAware {

	private ResourceLoader resourceLoader;

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

	@javax.annotation.Resource
	private UniqueServiceLocator serviceLocator;

	public Map<String, Integer> importSchemas(final String path) throws IOException {

		int done = 0;
		int total = 0;

		for (Resource res : ResourcePatternUtils.getResourcePatternResolver(getResourceLoader()).getResources(path)) {
			total++;
			try {
				registerSchema(res.getURL());
				done++;
			} catch (Throwable e) {
				log.error("Error registering schema " + res.getURL(), e);
			}
		}

		final Map<String, Integer> res = Maps.newHashMap();
		res.put("schemasDone", done);
		res.put("schemasTotal", total);

		return res;
	}

	public Map<String, Integer> importProfiles(final String path) throws IOException {

		int done = 0;
		int total = 0;

		for (Resource res : ResourcePatternUtils.getResourcePatternResolver(getResourceLoader()).getResources(path)) {
			total++;
			try {
				registerProfile(res.getURL());
				done++;
			} catch (Throwable e) {
				log.error("Error registering profile " + res.getURL(), e);
			}
		}

		final Map<String, Integer> res = Maps.newHashMap();
		res.put("profilesDone", done);
		res.put("profilesTotal", total);

		return res;
	}

	private void registerSchema(final URL url) throws Exception {
		final String resourceType = FilenameUtils.getBaseName(url.getPath());

		log.info("registering schema: " + resourceType);

		serviceLocator.getService(ISRegistryService.class).addResourceType(resourceType, IOUtils.toString(url.openStream()));
	}

	private void registerProfile(final URL url) throws Exception {
		final StreamOpaqueResource resource = new StreamOpaqueResource(url.openStream());
		final String name = resource.getResourceId().split("_")[0];
		final String coll = "/db/DRIVER/" + resource.getResourceKind() + "/" + resource.getResourceType();

		log.info("saving profile: " + name + " in coll " + coll);

		serviceLocator.getService(ISStoreService.class).insertXML(name, coll, resource.asString());
	}

	public ResourceLoader getResourceLoader() {
		return resourceLoader;
	}

	@Override
	public void setResourceLoader(final ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

}
