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.locators.UniqueServiceLocator;

@Controller
public class CommonController {

	@Resource
	private UniqueServiceLocator serviceLocator;

	@RequestMapping(value = "/ui/**/getProfile")
	public void getProfile(final HttpServletResponse res,
			@RequestParam(value = "id", required = true) final String id) throws Exception {
		res.setContentType("text/xml");
		String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(id);
		IOUtils.copy(new StringReader(profile), res.getOutputStream());
	}

	@RequestMapping(value = "/ui/**/getSchema")
	public void getSchema(final HttpServletResponse res,
			@RequestParam(value = "name", required = true) final String name) throws Exception {
		res.setContentType("text/xml");
		String schema = serviceLocator.getService(ISLookUpService.class).getResourceTypeSchema(name);
		IOUtils.copy(new StringReader(schema), res.getOutputStream());
	}

	@RequestMapping(value = "/ui/**/validateProfile")
	public void validate(final HttpServletResponse res,
			@RequestParam(value = "id", required = true) final String id) throws Exception {
		String newId = serviceLocator.getService(ISRegistryService.class).validateProfile(id);
		IOUtils.copy(new StringReader(new Gson().toJson(newId)), res.getOutputStream());
	}

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

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

}
