<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="org.eclipse.cosmos.internal.dr.drs.service.outputter.ReportDeploymentHandler" %>
<%@page import="org.eclipse.cosmos.internal.dr.drs.service.outputter.ReportElement" %>
<%@page import="org.w3c.dom.*" %>
<%@page import="java.util.*" %>
<%@page import="java.io.*" %>
<%@page import="javax.xml.transform.*" %>
<%@page import="javax.xml.transform.dom.*" %>
<%@page import="javax.xml.transform.stream.*" %>
<%@ taglib uri="/birt.tld" prefix="birt" %>
<%!
    ReportDeploymentHandler rdh;
    public void jspInit()
    {
      ServletContext context = this.getServletConfig().getServletContext();
	rdh = new ReportDeploymentHandler();
	rdh.parse(context.getRealPath("templates/reportDeployment.xml"));
    }

    public void jspDestroy()
    {
	rdh = null;
    }
%>
<% 
/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
String func = request.getParameter("func");
if ("list".equals(func)){

		Map<String,String> criteria = new HashMap<String, String>();
		Map parameters = request.getParameterMap();
		Iterator param = parameters.keySet().iterator();
		String paramStr= ""; //$NON-NLS-1$
		while (param.hasNext()){
			String key = (String)param.next();
			//need to handle datasource parameter as a special case
			if (key.startsWith("__p")){
				String value= request.getParameter(key.toString());
				if ((value != null) && (!("".equals(value))))
					criteria.put(key.substring(3, key.length()), value);
			}
		}
		List<ReportElement>  nodeList = rdh.getReportElementByMetaData(criteria);
		if (nodeList != null){
			out.print("["); //$NON-NLS-1$
			for (int x = 0; x < nodeList.size(); x++){
				ReportElement element = nodeList.get(x);
				if (x > 0)
					out.print(",");
				out.print("{\"caption\":\""+element.getMetaData("displayName")+"\",\"value\":\""+element.getId()+"\"}");			 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			}
			out.print("]"); //$NON-NLS-1$
		}
		else{
			out.print("[{}]"); //$NON-NLS-1$
		}
}
else{
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>COSMOS Report Viewer</title>
</head>
<body>
<%
//put xml datasource in session 
//check to see if we have a new data source
String uuidStr = request.getParameter("datasourceid");
if ("__UNKOWN__".equals(uuidStr)) uuidStr = null;
String xmlSource = request.getParameter("XML_DATASOURCE");
Node resultNode = null;
if (xmlSource != null){
      //generate unique key
	uuidStr = UUID.randomUUID().toString();
	session.setAttribute(uuidStr, xmlSource);
}
//next we check if we need to strip down the xml
String reportid = request.getParameter("reportid");
String recordidx = request.getParameter("recordidx");
String namespace = request.getParameter("namespace");
String mdrid = request.getParameter("mdrid");
String localid = request.getParameter("localid");
String isRel = request.getParameter("isRel");
//now we need to extract the namespace of the record that we want to render
if (recordidx != null){
	String xml = (String)session.getAttribute(uuidStr);
	NodeList resultNodeSet = null;
	if (isRel != null)
		resultNodeSet  = ReportDeploymentHandler.getStringFromXPath("/queryResult/edges/relationship/record", xml);
      else
		resultNodeSet  = ReportDeploymentHandler.getStringFromXPath("/queryResult/nodes/item/record", xml);
	resultNode = resultNodeSet.item((Integer.parseInt(recordidx)-1));
	NamedNodeMap map = resultNode.getAttributes();
	Node node  = map.getNamedItem("xmlns");
	if (node != null)	
		namespace = node.getTextContent();
}
else if ((mdrid != null) && (localid != null)){
	//if we don't have a record index lets serach the document for the localid and mdrid record
	String xml = (String)session.getAttribute(uuidStr);
	NodeList resultNodeSet = null;
	resultNodeSet  = ReportDeploymentHandler.getStringFromXPath("/queryResult/nodes/item", xml);
	resultNode = null;
	for (int x = 0; x < resultNodeSet.getLength(); x++){
		Element resultElem = (Element)resultNodeSet.item(x);
		Element instanceIdElem = null;
		Element recordElem = null;
		Element mdrIdElem = null;
		Element localIdElem = null;
		String mdrIdStr = null;
		String localIdStr = null;
		NodeList tempList = resultElem.getChildNodes();
		for (int y = 0; y < tempList.getLength(); y++){
			if (tempList.item(y).getNodeName().endsWith("instanceId"))
				instanceIdElem = (Element)tempList.item(y);
			else if (tempList.item(y).getNodeName().endsWith("record"))
				recordElem = (Element)tempList.item(y);			
		}
		if (instanceIdElem != null){
			tempList = instanceIdElem.getChildNodes();
			for (int y = 0; y < tempList.getLength(); y++){
				if (tempList.item(y).getNodeName().endsWith("mdrId"))
					mdrIdElem = (Element)tempList.item(y);
				else if (tempList.item(y).getNodeName().endsWith("localId"))
					localIdElem = (Element)tempList.item(y);			
			}

			Node child = null;
			if (mdrIdElem != null)
				child = mdrIdElem.getFirstChild();
			if (child != null)
				mdrIdStr = child.getNodeValue();
			if (localIdElem != null)
				child = localIdElem.getFirstChild();
			if (child != null)
				localIdStr = child.getNodeValue();
			if ((mdrIdStr != null) && (localIdStr != null) && (mdrIdStr.trim().equals(mdrid.trim())) && (localIdStr.trim().equals(localid.trim()))){
				recordidx = ""+(x+1);
				resultNode = recordElem;
				break;
			}
		}
 	}

	if (resultNode != null){
		NamedNodeMap map = resultNode.getAttributes();
		Node node  = map.getNamedItem("xmlns");
		namespace = node.getTextContent();
	}

}
//Now we find the report that is associated with the namespace
Map<String, String> map = new HashMap<String, String>();
if (namespace == null){
   //if we don't have a namespace use the report associated with  "http://cmdbf.org/schema/1-0-0/datamodel"
   namespace = "http://cmdbf.org/schema/1-0-0/datamodel";
}
map.put("namespace", namespace);

List<ReportElement>  result = rdh.getReportElementByMetaData(map);
//if we can't find a report use the raw xml report
if ((result == null) || (result.size() == 0)){
	map.put("namespace", "http://rawxml");
	result = rdh.getReportElementByMetaData(map);
	//should put xml fragment in session.
	if (resultNode != null){

       DOMSource domSource = new DOMSource(resultNode);
       StringWriter writer = new StringWriter();
       StreamResult sresult = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       transformer.transform(domSource, sresult);
	uuidStr = UUID.randomUUID().toString();
	session.setAttribute(uuidStr,  writer.toString());

	}
}
else if (reportid != null){
	ReportElement elem = rdh.getReportElementById(reportid);
	if (elem != null){
		result = new ArrayList<ReportElement>();
		result.add(elem);
	}
}
if (uuidStr == null) uuidStr ="__UNKOWN__";

if ((result != null) && (result.size() > 0)){
%>
<birt:viewer id="birtViewer" reportDesign="<%= result.get(0).getFilename() %>"
pattern="frameset"
isHostPage="true"
height="600"
width="800"
format="html">
<birt:param name="datasourceid" value="<%= uuidStr %>"></birt:param>
<% if (recordidx != null) {
 %>
<birt:param name="recordidx" value="<%= recordidx %>"></birt:param>
<% } %>
<% if (localid != null) { %>
<birt:param name="localid" value="<%= localid %>"></birt:param>
<% } %>
<% if (isRel != null) { %>
<birt:param name="isItem" value="false"></birt:param>
<% } else {%>
<birt:param name="isItem" value="true"></birt:param>
<% } %>
<% if (mdrid != null) { %>
<birt:param name="mdrid" value="<%= mdrid %>"></birt:param>
<% } %>
<%
	Map rparameters = request.getParameterMap();
	Iterator rparam = rparameters.keySet().iterator();
	String paramStr= ""; //$NON-NLS-1$
	while (rparam.hasNext()){
		String key = (String)rparam.next();
		//need to handle datasource parameter as a special case
		if (key.startsWith("__r")){
			String value= request.getParameter(key.toString());
			if ((value != null) && (!("".equals(value))))
%>
<birt:param name="<%= key.substring(3, key.length()) %>" value="<%= value %>"></birt:param>
<%		}
	}
%>
</birt:viewer>
<%
}
%>

</body>
</html>
<% } %>