package eu.dnetlib.functionality.modular.ui;

import java.io.StringReader;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.rmi.enabling.ISLookUpService;
import eu.dnetlib.rmi.enabling.ISRegistryService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CommonController {

	@Autowired
	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");
		final String profile = this.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");
		final String schema = this.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 {
		final String newId = this.serviceLocator.getService(ISRegistryService.class).validateProfile(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 {
		final boolean b = this.serviceLocator.getService(ISRegistryService.class).deleteProfile(id);
		IOUtils.copy(new StringReader(new Gson().toJson(b)), res.getOutputStream());
	}

}
