package eu.dnetlib.is.importer;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import eu.dnetlib.data.is.wf.model.WfProcessExecution;
import eu.dnetlib.data.is.wf.repository.WfProcessExecutionRepository;

@Service
public class WfHistoryImporter {

	private static final Log log = LogFactory.getLog(WfHistoryImporter.class);

	@Autowired
	private WfProcessExecutionRepository wfProcessExecutionRepository;

	public void load(final String path) throws Exception {
		final ObjectMapper mapper = new ObjectMapper();

		final JsonNode rootNode = mapper.readTree(new File(path));

		rootNode.forEach(wf -> saveWf(wf));
	}

	private void saveWf(final JsonNode node) {

		final WfProcessExecution wf = new WfProcessExecution();
		wf.setProcessId(node.get("system:processId").asText());
		wf.setName(node.get("system:wfName").asText());
		wf.setFamily(node.get("system:profileFamily").asText());

		if (node.has("dataprovider:id")) {
			wf.setDsId(node.get("dataprovider:id").asText());
		}
		if (node.has("dataprovider:name")) {
			wf.setDsName(node.get("dataprovider:name").asText());
		}
		if (node.has("dataprovider:interface")) {
			wf.setDsApi(node.get("dataprovider:interface").asText());
		}

		wf.setStartDate(new Date(NumberUtils.toLong(node.get("system:startDate").asText())));
		wf.setEndDate(new Date(NumberUtils.toLong(node.get("system:endDate").asText())));

		if (BooleanUtils.toBoolean(node.get("system:isCompletedSuccessfully").asText())) {
			wf.setStatus("success");
		} else {
			wf.setStatus("failure");
		}

		final Map<String, String> details = new LinkedHashMap<>();
		final Iterator<Entry<String, JsonNode>> fields = node.fields();
		while (fields.hasNext()) {
			final Entry<String, JsonNode> f = fields.next();
			if (f.getValue().isValueNode()) {
				details.put(f.getKey(), f.getValue().asText());
			}
		}

		wf.setDetails(details);

		wfProcessExecutionRepository.save(wf);

		log.info("Wf saved with id: " + wf.getProcessId());

	}
}
