package eu.dnetlib.enabling.is.store;

import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
import eu.dnetlib.enabling.is.registry.schema.OpaqueResourceValidator;
import eu.dnetlib.enabling.is.registry.schema.ValidationException;
import eu.dnetlib.enabling.is.store.rmi.ISStoreException;
import eu.dnetlib.enabling.is.store.rmi.ISStoreService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.tools.OpaqueResource;
import eu.dnetlib.enabling.tools.XQueryUtils;

/**
 * This class implements a bulk resource import, i.e. importing stuff straight into the store, bypassing checks and policies imposed by the
 * registry service.
 * 
 * TODO: move from registry based to store based.
 * 
 * @author marko
 * 
 */
public class BulkResourceImporter {

	/**
	 * xquery utils, needed to map resources with the xmldb collection names.
	 */
	private XQueryUtils xqueryUtils;

	/**
	 * service locator.
	 */
	private UniqueServiceLocator serviceLocator;

	/**
	 * resource validator.
	 */
	private OpaqueResourceValidator resourceValidator;

	/**
	 * set to false to skip validation.
	 */
	private boolean validating = true;

	/**
	 * bulk loading enabled.
	 */
	private boolean enabled = true;

	/**
	 * register a resource bypassing the checks.
	 * 
	 * @param resource
	 *            a resource
	 * @throws ISRegistryException
	 *             could happen
	 */
	public void importResource(final OpaqueResource resource) throws ISRegistryException {
		try {
			if (validating) {
				resourceValidator.validate(resource);
			}
			serviceLocator.getService(ISStoreService.class, true).insertXML(xqueryUtils.getFileName(resource), xqueryUtils.getCollectionAbsPath(resource),
					resource.asString());
		} catch (final ISStoreException e) {
			throw new ISRegistryException(e);
		} catch (final ValidationException e) {
			throw new ISRegistryException(e);
		}
	}

	public XQueryUtils getXqueryUtils() {
		return xqueryUtils;
	}

	@Required
	public void setXqueryUtils(final XQueryUtils xqueryUtils) {
		this.xqueryUtils = xqueryUtils;
	}

	@Required
	public void setResourceValidator(final OpaqueResourceValidator resourceValidator) {
		this.resourceValidator = resourceValidator;
	}

	public OpaqueResourceValidator getResourceValidator() {
		return resourceValidator;
	}

	public void setValidating(final boolean validating) {
		this.validating = validating;
	}

	public boolean isValidating() {
		return validating;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(final boolean enabled) {
		this.enabled = enabled;
	}

	public UniqueServiceLocator getServiceLocator() {
		return serviceLocator;
	}

	@Required
	public void setServiceLocator(final UniqueServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

}
