package eu.dnetlib.data.transformation.ui;

import java.io.IOException;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import eu.dnetlib.data.transformation.service.DataTransformerFactory;
import eu.dnetlib.data.transformation.service.SimpleDataTransformer;
import eu.dnetlib.enabling.inspector.AbstractInspectorController;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.functionality.modular.ui.error.ErrorMessage;

@Controller
public class DataTransformationController extends AbstractInspectorController {

	@Resource
	private DataTransformerFactory dataTransformerFactory;

	@Resource
	private TransformerUtils transformerUtils;

	@RequestMapping(value = "/inspector/transform.do")
	public void transform(final Model model,
			@RequestParam(value = "rule", required = false) final String ruleId,
			@RequestParam(value = "record", required = false) final String record) throws Exception {

		model.addAttribute("rules", transformerUtils.obtainRuleProfiles(ruleId));

		if (ruleId != null && record != null) {
			final SimpleDataTransformer transformer = dataTransformerFactory.createTransformer(ruleId);
			model.addAttribute("input", record);
			model.addAttribute("output", transformer.evaluate(record));
		}
	}

	@RequestMapping(value = "/ui/transform/transform.do")
	public void transform(final HttpServletResponse res,
			@RequestParam(value = "rule", required = true) final String ruleId,
			@RequestBody final String record) throws ISLookUpDocumentNotFoundException, ISLookUpException, IOException {
		res.setContentType("text/xml");
		IOUtils.write(dataTransformerFactory.createTransformer(ruleId).evaluate(record), res.getOutputStream());
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public @ResponseBody ErrorMessage handleException(final HttpServletRequest req, final Exception e) {
		return new ErrorMessage(e.getMessage(), ExceptionUtils.getStackTrace(e));
	}
}
