var entryNodeName = "CommonBaseEvent";

var startTag = "<" + entryNodeName;
var endTag = "</" + entryNodeName + ">";
var lcEntryNodeName = entryNodeName.toLowerCase();

function readEntry() {
	var cbe = readCBE(inp, entry);
	if (!cbe) {
		result.setStatus(0); // 0 = End-of-Data
		return;
	}

	mapCBE2Entry(cbe, entry);
	result.setStatus(1); // 1 = Here comes an Entry
}


// Global variables needed for readCBE()
// These are of course global to the Scripted Parser's 
// own JavaScript context, not that of the AL.
//
var str = "";
var cbeStr = new java.lang.StringBuffer();
var foundCBE = false;
var debug = false;




// Split up the multi-root CBE stream into separate
// blocks of xml, one for each CommonBaseEvent node
// 
function readCBE (inp, entry)
{
	do {
		if (!str) {
			str = inp.readLine();
		}

		if (str == null) {
			return null;
		}

		str = str.trim();

		if (!foundCBE) {
			p1 = str.indexOf(startTag);
			if (p1 >= 0) {	
				str = str.substring(p1, str.length-p1);
				cbeStr.setLength(0);
//				cbeStr.append(str);
				foundCBE = true;
			} else {
				str = null;
			}
		}

		if (foundCBE) {
			p1 = str.indexOf(endTag);
			if (p1 >= 0) {
				cbeStr.append(str.substring(0, p1+18))

				if ((p1+18) < str.length) {
					str = str.substring(p1+18).trim()
				} else {
					str = null;
				}
				
				foundCBE = false;
				entry.setAttribute("cbe", cbeStr.toString());
				result.setStatus(1); // 1 = Read an Entry
				return cbeStr;
			} else {
				cbeStr.append(str);
				str = "";
			}
		}
	} while (true);
}



function mapCBE2Entry(cbe, entry) {
	var xmldom = buildDOM(cbe);
	var root = xmldom.getDocumentElement ();
	var list = system.selectNodeList ( root,  "//" + entryNodeName );

	addAttributes(list.item(0), entry, "");	
}



function setAttribute( entry, attName, attValue ) {
if (debug)
	java.lang.System.out.println(" --> Adding " + attName + " = " + attValue);
	
	entry.setAttribute(attName, attValue);	
}


function buildDOM( xml ) {
	if (xml == null)
		main.logmsg("@@ ERROR: no XML_STRING found")
	else try {

if (debug) {
	main.logmsg("\n\n.*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*.\n" +
				" --------------  buildDOM( xml ) - xml = \n" + 
				xml.toString() + 
				"\n.*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*..*^^*.\n");

/*
    var ut = new java.io.FileWriter("c:/temp/cbe.xml");
    var bw = new java.io.BufferedWriter(ut);
	bw.write(xml.toString(), 0, xml.length());
	bw.flush();
	bw.close();
*/
}
	
		var dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
		var db = dbf.newDocumentBuilder();

		var bais = new java.io.ByteArrayInputStream(xml.toString().getBytes());

		var doc = db.parse(bais);
		doc.getDocumentElement().normalize();

		return doc;
	} catch (ex) {
		main.logmsg("** Error parsing xml: " + ex);
   		ex.printStackTrace();
	   	return null;
	}
}




function addAttributes(node, entry, name) {
	if (!node || !entry)
		return;

	var nodeName = node.getNodeName();
	var nodeType = node.getNodeType();

if (debug)
   java.lang.System.out.println("\n*********> addAttributes(     " + nodeName
			   + "    type: " + nodeType
			   + "    accum-name: " + name  + "  )");

	if (nodeType == 1) { // 1 = Element
	
		// First add Node attributes
		var atts = node.getAttributes();

		// If there is a "name" or "id" attribute, accumulate this value
  		// instead of the node name to make the Attribute name.
		if (atts) {
			for (var i = 0; i < atts.getLength(); i++) {
				var attNode = atts.item(i);
				var attName = attNode.getNodeName().trim();

				if (attName == "name" || attName == "id") {
					nodeName = attNode.getNodeValue();
					break;
				}
			}
		}

		if (!nodeName.equalsIgnoreCase(entryNodeName))
			name += ((name) ? "." : "") + nodeName;

if (debug)
	java.lang.System.out.println(" --> new name: " + name);

		if (atts) {
			for (var i = 0; i < atts.getLength(); i++) {
				var attNode = atts.item(i);
				var attName = attNode.getNodeName().trim();
				var attValue = attNode.getNodeValue();

				if (attName != "name" && attName != "id") {
					setAttribute(entry, name + ((name) ? "." : "") + attName, attValue)
                }
			}
		}
		
		// Now add children
		var children = node.getChildNodes();

		if (children) {
			for (var j = 0; j < children.getLength(); j++) {
				addAttributes(children.item(j), entry, name);
			}
		}
	} else if (nodeType == 3) { // 3 = Text
		setAttribute(entry, name, node.getNodeValue());
	}
}
