package eu.dnetlib.functionality.modular.ui.workflows.controllers;

import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.List;

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

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.ModelMap;

import com.google.gson.Gson;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.functionality.modular.ui.ModuleEntryPoint;
import eu.dnetlib.functionality.modular.ui.workflows.objects.sections.WorkflowSectionGrouper;

public class WfEntryPointController extends ModuleEntryPoint {

	@Resource
	private WorkflowSectionGrouper workflowSectionGrouper;

	@Resource
	private UniqueServiceLocator serviceLocator;

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

	private final Gson gson = new Gson();

	@Override
	protected void initialize(final ModelMap map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		if (request.getParameterMap().containsKey("wfId")) {
			initialize_direct_wf(map, request);
		} else {
			initialize_normal(map, request);
		}
	}

	private void initialize_direct_wf(final ModelMap map, final HttpServletRequest request) {

		final String wfId = request.getParameter("wfId");

		final StringWriter sw = new StringWriter();

		sw.append("for $x in collection('/db/DRIVER/MetaWorkflowDSResources/MetaWorkflowDSResourceType') ");
		sw.append("where $x//WORKFLOW/@id='");
		sw.append(wfId);
		sw.append("' return concat(");
		sw.append("$x//METAWORKFLOW_SECTION, ");
		sw.append("' |=@=| ', ");
		sw.append("$x//RESOURCE_IDENTIFIER/@value, ");
		sw.append("' |=@=| ', ");
		sw.append("$x//DATAPROVIDER/@id, ");
		sw.append("' |=@=| ', ");
		sw.append("$x//DATAPROVIDER/@interface)");

		try {
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(sw.toString());
			if (list.size() > 0) {
				final String[] arr = list.get(0).split("\\|=@=\\|");

				final String section = arr[0].trim();
				final String metaWf = arr[1].trim();
				final String repoId = arr[2].trim();
				final String repoApi = arr[3].trim();

				if (!StringUtils.isEmpty(repoId)
						&& !StringUtils.isEmpty(repoApi)
						&& !StringUtils.isEmpty(metaWf)
						&& !StringUtils.isEmpty(wfId)) {
					map.addAttribute("redirect",
							"repoApis.do#/api/" +
									URLEncoder.encode(repoId, "UTF-8") + "/" +
									URLEncoder.encode(repoApi, "UTF-8") + "/" +
									URLEncoder.encode(metaWf, "UTF-8") + "/" +
									URLEncoder.encode(wfId, "UTF-8"));

				} else {
					map.addAttribute("initialWf", gson.toJson(wfId));
					map.addAttribute("initialMetaWf", gson.toJson(metaWf));
					map.addAttribute("section", gson.toJson(section));
				}
			}
		} catch (Exception e) {
			log.error("Error obtaining details of wf " + wfId);
		}
	}

	private void initialize_normal(final ModelMap map, final HttpServletRequest request) {
		if (request.getParameterMap().containsKey("section")) {
			map.addAttribute("section", gson.toJson(request.getParameter("section")));
		}
		if (request.getParameterMap().containsKey("metaWf")) {
			map.addAttribute("initialMetaWf", gson.toJson(request.getParameter("metaWf")));
		}
	}

}
