package eu.dnetlib.parthenos.publisher;

import java.io.IOException;
import java.net.URISyntaxException;

import eu.dnetlib.parthenos.jrr.JRRPublisherHelper;
import eu.dnetlib.parthenos.publisher.ParthenosPublisherHelper.ParthenosTargets;
import freemarker.template.TemplateException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ParthenosPublisherController {

	private static final Log log = LogFactory.getLog(ParthenosPublisherController.class);
	//TODO: to nicely handle arrors, follow https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling

	@Autowired
	private ParthenosPublisherHelper parthenosPublisherHelper;

	@Autowired
	private JRRPublisherHelper jrrPublisherHelper;

	@RequestMapping(value="publishJRR", method = RequestMethod.POST)
	public int publishJRR(@RequestParam final String typeNamespace, @RequestParam final String typeName, @RequestParam final String datasourceApi, @RequestParam final String datasourceName)
			throws URISyntaxException, TemplateException, IOException, InterruptedException, ParthenosPublisherException {
		return jrrPublisherHelper.publish(typeNamespace, typeName, datasourceApi, datasourceName);
	}

	@RequestMapping(value = "/publish", method = RequestMethod.POST)
	public void publish(@RequestParam final String record, @RequestParam(required = false) String parthenosTarget) throws ParthenosPublisherException {
		getParthenosPublisherHelper().publish(record, getTarget(parthenosTarget));
	}


	@RequestMapping(value = "/unpublish", method = RequestMethod.GET)
	public void unpublish(@RequestParam final String datasourceApi, @RequestParam(required = false) String parthenosTarget) throws ParthenosPublisherException {
		getParthenosPublisherHelper().unpublish(datasourceApi, getTarget(parthenosTarget));
	}

	@RequestMapping(value = "/dropRegistry", method = RequestMethod.GET)
	public void unpublish(@RequestParam final int bulkSize) throws ParthenosPublisherException {
		getParthenosPublisherHelper().dropRegistry(bulkSize);
	}

	private ParthenosTargets getTarget(String value) {
		return ParthenosTargets.valueOf(value);
	}

	public ParthenosPublisherHelper getParthenosPublisherHelper() {
		return parthenosPublisherHelper;
	}

	public void setParthenosPublisherHelper(final ParthenosPublisherHelper parthenosPublisherHelper) {
		this.parthenosPublisherHelper = parthenosPublisherHelper;
	}

	public JRRPublisherHelper getJrrPublisherHelper() {
		return jrrPublisherHelper;
	}

	public void setJrrPublisherHelper(JRRPublisherHelper jrrPublisherHelper) {
		this.jrrPublisherHelper = jrrPublisherHelper;
	}
}