package engine;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sleepycat.dbxml.XmlContainer;
import com.sleepycat.dbxml.XmlDocument;
import com.sleepycat.dbxml.XmlException;
import com.sleepycat.dbxml.XmlManager;

public class OracleXMLConnector {
	// This function is used to ensure that databases are
	// properly closed, even on exceptions
	private static void cleanup(XmlManager mgr, XmlContainer cont) {
		try {
			if (cont != null)
				cont.delete();
			if (mgr != null)
				mgr.delete();
		} catch (Exception e) {
			// ignore exceptions in cleanup
		}
	}

	public int InsertXML(Element invoice, int invoiceID) {
		int result = 0;
		// An empty string means an in-memory container, which
		// will not be persisted
		String containerName = "invoice.dbxml";
		String content = ""; // "<hello>Hello World</hello>";
		String docName = "invoice_" + invoiceID;
		XmlManager mgr = null;
		XmlContainer cont = null;
		try {
			content = OracleConnector.TransformToString(invoice);

			// All BDB XML programs require an XmlManager instance
			mgr = new XmlManager();
			// Because the container will exist on disk, remove it
			// first if it exists
			// THE METHOD DOESN'T WORK
			try{
			mgr.removeContainer(containerName);
			}catch(Exception ex){}
			if (mgr.existsContainer(containerName) == 0) {
				// Now it is safe to create the container
				cont = mgr.createContainer(containerName);
			} else {
				// cont = mgr.createContainer(containerName);
				cont = mgr.openContainer(containerName);
			}

			cont.putDocument(docName, content);
			result = 1;
		} catch (XmlException xe) {
			System.err.println("XmlException during HelloWorld: "
					+ xe.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			cleanup(mgr, cont);
		}
		return result;
	}

	private String SelectXMLData(int invoiceID) {
		// An empty string means an in-memory container, which
		// will not be persisted
		String containerName = "invoice.dbxml";
		String docName = "invoice_" + invoiceID;
		XmlManager mgr = null;
		XmlContainer cont = null;
		String docContent = "";
		try {

			// All BDB XML programs require an XmlManager instance
			mgr = new XmlManager();
			// Because the container will exist on disk, remove it
			// first if it exists
			// THE METHOD DOESN'T WORK
			// mgr.removeContainer(containerName);
			if (mgr.existsContainer(containerName) == 0) {
				// Now it is safe to create the container
				cont = mgr.createContainer(containerName);
			} else {
				// cont = mgr.createContainer(containerName);
				cont = mgr.openContainer(containerName);
			}

			// Now, get the document
			XmlDocument doc = cont.getDocument(docName);
			String name = doc.getName();
			docContent = doc.getContentAsString();

			// print it
			System.out.println("Document name: " + name + "\nContent: "
					+ docContent);

		} catch (XmlException xe) {
			System.err.println("XmlException during HelloWorld: "
					+ xe.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			cleanup(mgr, cont);
		}
		return docContent;
	}

	public Document SelectXML(int invoiceID) throws ParserConfigurationException, SAXException, IOException {
		String xmlRecords = SelectXMLData(invoiceID);
		DocumentBuilder db = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		InputSource is = new InputSource();
		is.setCharacterStream(new StringReader(xmlRecords));

		Document doc = db.parse(is);
		
		return doc;
	}
}
