package eu.dnetlib.enabling.inspector;

import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Resource;

import eu.dnetlib.xml.database.XMLDatabase;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xmldb.api.base.XMLDBException;

/**
 * This controller offers a simple way to run arbitrary queries on the xmldb.
 *
 * @author marko
 *
 */
@Controller
public class QueryController extends AbstractInspectorController {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(QueryController.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * xmldb.
	 */
	@Resource(name = "existDatabase")
	private transient XMLDatabase xmlDatabase;
	
	/**
	 * utility to parse resource ids and allows to navigate them.
	 */
	@Resource(name = "resourcelinkTool")
	private ResourceLinkTool linkTool;	

	/**
	 * run a query.
	 *
	 * @param model
	 *            mvc model
	 * @param query
	 *            query (optional)
	 * @throws
	 */
	@RequestMapping(value = "/inspector/query.do")
	void query(final Model model, @RequestParam(value = "query", required = false) final String query) {
		if (query != null) {
			log.info("running query: " + query);

			try {
				final Iterator<String> it = xmlDatabase.xquery(query);
				final List<String> res = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.IMMUTABLE), false)
						.map(StringEscapeUtils::escapeHtml4)
						.map(linkTool::linkfyToHtml)
						.collect(Collectors.toList());

				model.addAttribute("size", res.size());
				model.addAttribute("results", res);
			} catch (XMLDBException e) {
				model.addAttribute("message", "failed: " + e.getMessage());
			}
		}

		model.addAttribute("query", query);

	}

}
