package eu.dnetlib.functionality.modular.ui;

import java.io.StringReader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.tools.ServiceLocator;

@Controller
public class CommonController {
	
	@Resource(name="lookupLocator")
	private ServiceLocator<ISLookUpService> lookupLocator;

	@Resource(name="registryLocator")
	private ServiceLocator<ISRegistryService> registryLocator;

	@RequestMapping(value="/ui/**/getProfile")
	public void getProfile(HttpServletResponse res, 
			@RequestParam(value="id", required=true) String id) throws Exception {
		res.setContentType("text/xml");
		String profile = lookupLocator.getService().getResourceProfile(id);
		IOUtils.copy(new StringReader(profile), res.getOutputStream());
	}
	
	@RequestMapping(value="/ui/**/getSchema")
	public void getSchema(HttpServletResponse res, 
				@RequestParam(value="name", required=true) String name) throws Exception {
		res.setContentType("text/xml");
		String schema = lookupLocator.getService().getResourceTypeSchema(name);
		IOUtils.copy(new StringReader(schema), res.getOutputStream());
	}
	
	@RequestMapping(value="/ui/**/validateProfile")
	public void validate(HttpServletResponse res, 
			@RequestParam(value="id", required=true) String id) throws Exception {
		String newId = registryLocator.getService().validateProfile(id);
		IOUtils.copy(new StringReader(new Gson().toJson(newId)), res.getOutputStream());
	}

	@RequestMapping(value="/ui/**/invalidateProfile")
	public void invalidateProfile(HttpServletResponse res, 
			@RequestParam(value="id", required=true) String id) throws Exception {
		String newId = registryLocator.getService().invalidateProfile(id);
		IOUtils.copy(new StringReader(new Gson().toJson(newId)), res.getOutputStream());
	}
	
	@RequestMapping(value="/ui/**/deleteProfile")
	public void deleteProfile(HttpServletResponse res, 
			@RequestParam(value="id", required=true) String id) throws Exception {
		boolean b = registryLocator.getService().deleteProfile(id);
		IOUtils.copy(new StringReader(new Gson().toJson(b)), res.getOutputStream());
	}
		
}
