package eu.dnetlib.is.importer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.common.controller.AbstractDnetController;
import eu.dnetlib.data.is.vocabulary.model.Vocabulary;

@RestController
@RequestMapping("/api/import")
public class ImporterController extends AbstractDnetController {

	// EXAMPLE:
	// find ./VocabularyDSResourceType/ -name "*.xml" -exec curl -X POST "http://localhost:8280/api/import/vocabulary" -H "accept: */*" -H
	// "Content-Type: text/plain" --data-binary @{} \;
	// find ./DedupConfigurationDSResources/ -name "*.xml" -exec curl -X POST "http://localhost:8280/api/import/resource" -H "accept: */*"
	// -H "Content-Type: text/plain" --data-binary @{} \;

	@Autowired
	private ContextImporter contextImporter;

	@Autowired
	private OldProfilesImporter oldProfilesImporter;

	@Autowired
	private WfHistoryImporter wfHistoryImporter;

	@PostMapping(value = "/context", consumes = {
		MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE
	})
	public List<String> importContext(final HttpServletRequest request) throws DocumentException, IOException {

		final String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);

		contextImporter.loadFromOldProfile(xml);

		return Arrays.asList("Done.");

	}

	@PostMapping(value = "/resource", consumes = {
		MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE
	})
	public String importResource(final HttpServletRequest request) throws Exception {
		final String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);

		return oldProfilesImporter.importSimpleResource(xml);
	}

	@PostMapping(value = "/vocabulary", consumes = {
		MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE
	})
	public Vocabulary importVocabulary(final HttpServletRequest request) throws Exception, IOException {
		final String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
		return oldProfilesImporter.importVocabulary(xml);
	}

	@GetMapping(value = "/wf_logs")
	public List<String> importWfLogs(@RequestParam final String path) throws Exception {
		// mongoexport -d dnet_logs -c wf_logs --jsonArray -o /tmp/mongodump.json

		wfHistoryImporter.load(path);

		return Arrays.asList("Done.");
	}
}
