package eu.dnetlib.validator2.engine;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public class CrisClass {

    private String classId;
    private String ClassSchemeId;
    private String startDate;
    private String endDate;

    // Maybe will change to constructor calling the private default constructor. Will see
    public static CrisClass getInstance(Node node) throws XPathExpressionException, ParserConfigurationException {
        CrisClass instance = new CrisClass();

        Document newXMLDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element root = newXMLDocument.createElement("root");
        newXMLDocument.appendChild(root);
        Node copyNode = newXMLDocument.importNode(node, true);
        root.appendChild(copyNode);
        printXMLDocument(newXMLDocument);

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        instance.setClassId((String) xPath.evaluate("//cfClassId/text()", newXMLDocument, XPathConstants.STRING));
        instance.setClassSchemeId((String) xPath.evaluate("//cfClassSchemeId/text()", newXMLDocument, XPathConstants.STRING));
        instance.setStartDate((String) xPath.evaluate("//cfStartDate/text()", newXMLDocument, XPathConstants.STRING));
        instance.setEndDate((String) xPath.evaluate("//cfEndDate/text()", newXMLDocument, XPathConstants.STRING));

        return instance;
    }

    // Not sure of the effect of this method. Implemented as in the original source.
    private static void printXMLDocument(Document document) {
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) document.getImplementation();
        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        lsSerializer.writeToString(document);
    }

    private CrisClass() {}

    public String getClassId() {
        return classId;
    }

    public void setClassId(String classId) {
        this.classId = classId;
    }

    public String getClassSchemeId() {
        return ClassSchemeId;
    }

    public void setClassSchemeId(String classSchemeId) {
        ClassSchemeId = classSchemeId;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
}
