package com.k_int.npdb.util;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.xpath.CachedXPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WebUtils{
	
	public String solrURL;
	
	public  void setSolrURL(String solrURL) {
		this.solrURL = solrURL;
	}

	public  String renderDescription(String description)
	{
		
		Map<String, String> list = extractLinks(description);
		String url = "<a href='/npdb/contributor?id=$id'>$name</a>";
		for (String name: list.keySet())
		{
			description = description.replace("["+ name + "]", url.replace("$id", list.get(name)).replace("$name", name));
		}
		return description;
	}
	
	private Map<String, String> extractLinks(String desc) {

		Map<String, String> list = new HashMap<String, String>();
		try{
		while (desc.matches(".*\\[.*\\].*")) {
			
			int start = desc.indexOf("[");
			int end = desc.indexOf("]", start);
			String name = desc.substring(start+1, end);
			String query = " AND name:" + name;
			Document d = SOLRUtils.search(solrURL + "/select/?q=type:person"+ URLEncoder.encode(query,"UTF-8") +"&version=2.2&start=0&rows=10");
			CachedXPathAPI api = new CachedXPathAPI();
			NodeList elements =  api.selectNodeList(d,"/response/result/doc");
			if (elements.getLength() > 0)
			{	
				Node n = elements.item(0);
				String internalId = XMLUtils.getString(n, "long[@name='internalId']");
				list.put(name, internalId);
			}
			desc = desc.substring(end);
		}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
		
}