/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package peaconnector;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Csubák Péter
 */
public class PeaConnector {

    private String sessionID = null;
    private URL serverUrl = null;
    private String schemaName = null;

    public PeaConnector(URL serverUrl, String schemaName) {
        this.serverUrl = serverUrl;
        this.schemaName = schemaName;
    }

    public String startSession(Class clazz) throws RemoteException {
        String outXml = null;
        Document inXml = null;
        if (sessionID == null) {
            outXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><m>" +
                    "<cname>" + clazz.getSimpleName() + "</cname>" +
                    "<create />" +
                    "<schname>" + schemaName + "</schname></m>";
        } else {
            outXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><m>" +
                    "<sid>" + sessionID + "</sid>" +
                    "<cname>" + clazz.getSimpleName() + "</cname>" +
                    "<create />" +
                    "<schname>" + schemaName + "</schname></m>";
        }

        HttpRequest hr = new HttpRequest(serverUrl, outXml);
        hr.setMethod("POST");
        if (hr.sendRequest()) {
            int index = hr.getAnswer().indexOf("<?");
            String xml = hr.getAnswer().substring(index);
            InputStream in = null;
            try {
                in = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
            }
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                inXml = db.parse(in);
            } catch (Exception e) {
                throw new PeaException("The response is not an xml document.");
            }
        }

        String res = null;

        if (inXml != null){
            Node xml = inXml.getFirstChild();
            NodeList nl = xml.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++){
                Node node = nl.item(i);
                if (node.getNodeName().equals("sid")){
                    if (!(node.getTextContent().equals("null") || node.getTextContent().equals(""))){
                        this.sessionID = node.getTextContent();
                    }
                }else if (node.getNodeName().equals("oid")){
                    res = node.getTextContent();
                }else if (node.getNodeName().equals("result")){
                    if (!(node.getTextContent().equals("null") || node.getTextContent().equals(""))){
                        throw XmlSerializer.deserializeException(node.getFirstChild());
                    }
                }
            }
        }

        return res;
    }

    public Node sendMethodCall(String serializedMethod, Class clazz, String ROID) {
        String outXml = null;
        Document inXml = null;
        if (sessionID == null) {
            outXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><m>" +
                    "<cname>" + clazz.getSimpleName() + "</cname>" +
                    "<mc>"+serializedMethod+"</mc></m>";
        } else {
            outXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><m>" +
                    "<sid>" + sessionID + "</sid>" +
                    "<oid>"+ROID+"</oid>" +
                    ""+serializedMethod+"</m>";
        }

        HttpRequest hr = new HttpRequest(serverUrl, outXml);
        hr.setMethod("POST");
        if (hr.sendRequest()) {
            //TESZT NEM ITTHAGYNI!!!
            System.out.println(hr.getAnswer());

            
            int index = hr.getAnswer().indexOf("<?");
            String xml = hr.getAnswer().substring(index);
            InputStream in = null;
            try {
                in = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
            }
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                inXml = db.parse(in);
            } catch (Exception e) {
                throw new PeaException("The response is not an xml document.");
            }
        }

        if (inXml != null){
            Node xml = inXml.getFirstChild();
            NodeList nl = xml.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++){
                Node node = nl.item(i);
                if (node.getNodeName().equals("sid")){
                    if (!(node.getTextContent().equals("null") || node.getTextContent().equals(""))){
                        this.sessionID = node.getTextContent();
                    }
                }else if (node.getNodeName().equals("result")){
                    return node;
                }
            }
        }

        return null;
    }

    public void endSession() {
    }

    public String getSchemaName() {
        return schemaName;
    }
}
