package eu.dnetlib.data.claimsDemo;

import eu.dnetlib.api.enabling.ISLookUpService;
import eu.dnetlib.data.claims.migration.handler.ClaimHandler;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by kiatrop on 27/1/2016.
 */
public class ContextUtils {
    private static final Logger logger = Logger.getLogger(ClaimHandler.class);

        private static Document document = null;

        //private static String isLookUpAddress = "http://node6.t.openaire.research-infrastructures.eu:8280/is/services/isLookUp";
        //String registryAddress = "http://node6.t.openaire.research-infrastructures.eu:8280/is/services/isRegistry";

    private ISLookUpService isLookUpService = null;

    static {

        InputStream inputStream = ContextUtils.class.getClassLoader().getResourceAsStream("eu/dnetlib/data/claimsDemo/egi.xml");

        DocumentBuilderFactory factory =  DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();

        } catch (ParserConfigurationException e) {
            logger.error("Parse configuration Exception",e);
        }

        //StringBuilder xmlStringBuilder = new StringBuilder();
        try {
            document = builder.parse(inputStream);

        } catch (SAXException e) {
            logger.error("SAXException",e);

        } catch (IOException e) {
            logger.error("IOException",e);
        }
    }

    public static String extractEgiLabel(String code) throws XPathExpressionException {
        String[] codeParts = code.split("::");
        StringBuilder builder = new StringBuilder();

        StringBuilder reconstructedCode = new StringBuilder();
        if (codeParts.length > 0) {
            reconstructedCode.append(codeParts[0]);
        }

        for(int i=0; i< codeParts.length; i++) {
            if (i == 0) {
                //System.out.println("1");
                builder.append(findContextLabel(reconstructedCode.toString()));

            } else if (i == 1) {
                reconstructedCode.append("::").append(codeParts[1]);
                builder.append("> ").append(findCategoryLabel(reconstructedCode.toString()));

            } else {
                reconstructedCode.append("::").append(codeParts[i]);
                builder.append("> ").append(findConceptLabel(reconstructedCode.toString()));
            }
        }

        return builder.toString();
    }


    private static String findContextLabel(String conceptCode) throws XPathExpressionException {
//        System.out.println("concept code: " + conceptCode) ;
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        XPathExpression expr = xpath.compile("//context[@id='"+ conceptCode + "']");
        NodeList nodeList = (NodeList)expr.evaluate(document,  XPathConstants.NODESET);

        Node nNode = nodeList.item(0);
        return nNode.getAttributes().getNamedItem("label").getTextContent();
    }

    private static String findCategoryLabel(String categoryCode) throws XPathExpressionException {
//      System.out.println("Category code: " + categoryCode) ;
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        XPathExpression expr = xpath.compile("//category[@id='"+ categoryCode + "']");
        NodeList nodeList = (NodeList)expr.evaluate(document,  XPathConstants.NODESET);

        Node nNode = nodeList.item(0);
        return nNode.getAttributes().getNamedItem("label").getTextContent();
    }

    private static String findConceptLabel(String conceptCode) throws XPathExpressionException {
//        System.out.println("Concept code: " + conceptCode) ;
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        XPathExpression expr = xpath.compile("//concept[@id='"+ conceptCode + "']");
        NodeList nodeList = (NodeList)expr.evaluate(document,  XPathConstants.NODESET);

        Node nNode = nodeList.item(0);
        return nNode.getAttributes().getNamedItem("label").getTextContent();
    }

}
