package eu.dnetlib.enabling.inspector;

import java.io.IOException;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.xml.sax.SAXException;

import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.tools.CompatResourceIdentifierResolverImpl;
import eu.dnetlib.enabling.tools.OpaqueResource;
import eu.dnetlib.enabling.tools.ResourceIdentifierResolver;
import eu.dnetlib.enabling.tools.StringOpaqueResource;

/**
 * This inspector allows the admin to quickly register a profile, like a repository profile.
 * 
 * @author marko
 * 
 */
@Controller
public class RegistryController extends AbstractInspectorController {

	@Resource
	private UniqueServiceLocator serviceLocator;

	/**
	 * manages resource identifier mappings with the abstract xmldb namespace (files/collections).
	 */
	@Resource
	private ResourceIdentifierResolver resIdResolver = new CompatResourceIdentifierResolverImpl();

	@RequestMapping(value = "/inspector/registerProfile.do", method = RequestMethod.GET)
	public void registerProfile() {}

	@RequestMapping(value = "/inspector/registerProfile2.do", method = RequestMethod.POST)
	public String doRegisterProfile(
			@RequestParam(value = "source") final String source,
			@RequestParam(value = "valid", required = false) final String valid,
			@RequestParam(value = "pending", required = false) final String pending) throws ISRegistryException, XPathExpressionException, SAXException,
			IOException, ParserConfigurationException {

		String id = null;

		if (valid != null && !"".equals(valid)) {
			id = serviceLocator.getService(ISRegistryService.class, true).registerProfile(source);
		} else {
			id = serviceLocator.getService(ISRegistryService.class, true).insertProfileForValidation(resourceTypeFor(source), source);
		}

		String collection = resIdResolver.getCollectionName(id);
		String file = resIdResolver.getFileName(id);

		return "redirect:index.do/db/DRIVER/" + collection + "/" + file + "/show";
	}

	private String resourceTypeFor(final String source) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {
		OpaqueResource resource = new StringOpaqueResource(source);
		return resource.getResourceType();
	}

}
