/**********************************************************************
 * Copyright (c) 2007, 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 - Initial API and implementation
 *
 * $Id: ReportDeploymentHandler.java,v 1.6 2008/08/20 19:42:13 sleeloy Exp $
 **********************************************************************/
package org.eclipse.cosmos.internal.dr.drs.service.outputter;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

/**
 * Parses the deployment report file: 
 * <pre>
 * <reports> 
 *    <report type="CBE">
 *       <template file="LogReport.rptdesign"/> 
 *    </report>
 *    <report>
 *       <template file="StatReport.rptdesign"/> 
 *    </report>
 *  </reports>
 * </pre>
 * @author sleeloy
 * 
 */
public class ReportDeploymentHandler {

	public static final String XPATHROOT="/visualizationMetadata/visualization";

	protected Document doc;
	protected XPathFactory xpathFactory = XPathFactory.newInstance();

	public void parse(String filename) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(true); // never forget this!
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(filename);

		} catch (ParserConfigurationException e) {
			fatalError(e);
		} catch (SAXNotRecognizedException e) {
			fatalError(e);
		} catch (SAXNotSupportedException e) {
			fatalError(e);
		} catch (SAXException e) {
			fatalError(e);
		} catch (IOException e) {
			fatalError(e);
		}

	}

	protected void fatalError(Exception e) {
		e.printStackTrace();
//		logger.error(e.getMessage(), e);
	}
	
	public List<ReportElement>  getReportElementByMetaData(Map<String, String> searchCriteria){
			Iterator<String> searchIter = searchCriteria.keySet().iterator();
			String xpathCriteria = "";
			int x = 0;
			while (searchIter.hasNext()){
				String key = searchIter.next();
				String value = searchCriteria.get(key);
				if (x > 0)
					xpathCriteria += " and ";
				xpathCriteria += "visualizationDescription/"+key+"/text()='"+value+"'";
				x++;
			}
			try {
				XPath xpath = xpathFactory.newXPath();
				XPathExpression expr = xpath.compile(XPATHROOT+"["+xpathCriteria+"]");
				NodeList list = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
				List<ReportElement> returnList = new ArrayList<ReportElement>();
				for (int y = 0; y < list.getLength(); y++){
					returnList.add(new ReportElement((Element)list.item(y)));
				}				
				return returnList;
			} catch (XPathExpressionException e) {
				fatalError(e);
			}

		return null;
	}
	
	public ReportElement getReportElementById(String id){

		try {
			XPath xpath = xpathFactory.newXPath();
			XPathExpression expr = xpath.compile(XPATHROOT+"[visualizationId/localId/text()='"+id+"']");
			NodeList list = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
			if ((list != null) && (list.getLength() > 0))
				return new ReportElement((Element)list.item(0));
			return null;
		} catch (XPathExpressionException e) {
			fatalError(e);
		}
		return null;
	}

	public static NodeList getStringFromXPath(String xpathExpression, String xml) throws Exception{
		DocumentBuilderFactory docfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docbuilder = docfactory.newDocumentBuilder();

		Document docroot = docbuilder.parse(new InputSource(new StringReader(xml)));
		
		XPath xpath = XPathFactory.newInstance().newXPath();
		NodeList resultNode = (NodeList) xpath.evaluate(xpathExpression, docroot, XPathConstants.NODESET);
		return resultNode;
	}
	
  public static String xmlToString(Node elem) throws Exception
	  {
	      StringWriter sw = new StringWriter();
	      Transformer serializer = TransformerFactory.newInstance().newTransformer();
          serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
          serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");	      	       //$NON-NLS-1$ //$NON-NLS-2$
	      serializer.transform(new DOMSource(elem), new StreamResult(sw));
	      return sw.toString();
	  }	
	
	public static final void main(String argv[]) throws Exception{
//			ReportDeploymentHandler rdh = new ReportDeploymentHandler();
//			rdh.parse("D:\\development\\wtp30\\eclipse\\Integrationworkspace3\\org.eclipse.cosmos.examples.e2e.dr.template\\WebContent\\templates\\reportDeployment.xml");
//			
//			Map<String, String> map = new HashMap<String, String>();
////			map.put("type", "TomcatSet");
//			map.put("namespace", "http://statistical/stat");
//			List<ReportElement>  result = rdh.getReportElementByMetaData(map);
//			if (result != null){
//				for (int i = 0; i < result.size(); i++) {
//					System.out.println(result.get(i).getFilename());
//				    System.out.println(result.get(i).getMetaData("namespace")); 
//				}			
//			}
		FileInputStream fis = new FileInputStream("D:\\development\\BIRT222\\eclipse\\workspace3\\GraphResponseProject\\response.xml");
		StringBuffer sb = new StringBuffer();
		int x= fis.available();
		byte b[]= new byte[x];
		fis.read(b);
		String content = new String(b);
		sb.append(content);		
		String xml = sb.toString();
		NodeList resultNodeSet  = ReportDeploymentHandler.getStringFromXPath("/queryResult/nodes/item/record", xml);
		for (int y= 0; y < resultNodeSet.getLength(); y++){
			Node resultNode = resultNodeSet.item(y);
			NamedNodeMap map = resultNode.getAttributes();
			Node node  = map.getNamedItem("xmlns");
			
//			System.out.println(node.getTextContent());
			System.out.println(xmlToString(resultNode.getChildNodes().item(1)));
			
			
		}

	}
}
