/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.tools.admingui.tree;

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;
import org.w3c.dom.Document;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.servlet.*;

import com.iplanet.jato.RequestContext;
import com.sun.enterprise.tools.guiframework.view.ViewXMLEntityResolver;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;

import com.sun.enterprise.tools.admingui.util.Util;
import com.sun.enterprise.tools.admingui.util.MBeanUtil;

public class TreeReader {
    private static final String OUTPUT_ENCODING = "UTF-8";
    private Document doc;
    private static HashMap nodeClasses = new HashMap();
    
    public TreeReader(InputStream is, String dtdURLBase) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        dbf.setIgnoringComments(false);
        dbf.setIgnoringElementContentWhitespace(false);
        dbf.setCoalescing(false);
        // The opposite of creating entity ref nodes is expanding them inline
        dbf.setExpandEntityReferences(true);
        
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new ViewXMLEntityResolver());

        OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, OUTPUT_ENCODING);
        db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
	doc = db.parse(is, dtdURLBase);
    }
    
    /**
     * Recursive routine to process DOM tree nodes
     */
    public static boolean process(Node n, IndexTreeModel treeModel, IndexTreeNode parent) {
        boolean hasChildren = false;
        for (Node child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
            String nodeName = child.getNodeName();
            if (nodeName.equalsIgnoreCase("Node")) {
                IndexTreeNode treeNode = addToTree((Element)child, treeModel, parent);
                process(child, treeModel, treeNode);
                hasChildren = true;
            }
            else if (nodeName.equalsIgnoreCase("DynamicNode")) {
                parent.setDynamicChild((Element)child);
                hasChildren = true;
            }
            else if (nodeName.equalsIgnoreCase("TreeNodeType")) {
                process((Element)child);
            }
        }
        return hasChildren;
    }
    
    private static void process(Element treeNodeType) {
        String name = treeNodeType.getAttribute("name");
        String clazz = treeNodeType.getAttribute("treeNodeClass");
        nodeClasses.put(name, clazz);
    }
    
    public static String getClass(String nodeClassType) {
        return (String) nodeClasses.get(nodeClassType);
    }
    
    private static IndexTreeNode addToTree(Element node, IndexTreeModel treeModel, IndexTreeNode parent) {
        String name = node.getAttribute("name"); // name is required attribute
        if (name.startsWith("$")) {
            int i = name.indexOf('#');
            if (i > 0) {
                String mbeanName = name.substring(1,i);
                String attrName = name.substring(i+1, name.length());
                name = (String)MBeanUtil.getAttribute(mbeanName, attrName);
            }
        } /*else {
            
            name = Util.getMessage(name); // get the I18N value.
        } */
        String nodeType = node.getAttribute("type");
        if (nodeType == null)
            nodeType = treeModel.CONTAINER;

        if ((parent == null && nodeType.equalsIgnoreCase(treeModel.ROOT) == false) ||
            (parent != null && nodeType.equalsIgnoreCase(treeModel.ROOT))) {
            throw new RuntimeException("The first node declared must be of type \"root\" and\n" +
                                       "there can be only one root node.");
        }

        IndexTreeNode treeNode = 
            IndexTreeNode.createNode(node, parent, nodeType, name, treeModel);
        return treeNode;
    }
    
    public void populate(IndexTreeModel treeModel) throws Exception {
        for (Node child = doc.getFirstChild(); child != null; 
                    child = child.getNextSibling()) {
            String nodeName = child.getNodeName();
            if (nodeName.equalsIgnoreCase("Tree"))
                process(child, treeModel, null);
        }
    }
    
    // Error handler to report errors and warnings
    private static class MyErrorHandler implements ErrorHandler {
        /** Error handler output goes here */
        private PrintWriter out;
        
        MyErrorHandler(PrintWriter out) {
            this.out = out;
        }
        
        /**
         * Returns a string describing parse exception details
         */
        private String getParseExceptionInfo(SAXParseException spe) {
            String systemId = spe.getSystemId();
            if (systemId == null) {
                systemId = "null";
            }
            String info = "URI=" + systemId + " Line=" + spe.getLineNumber() +  ": " + spe.getMessage();
            return info;
        }
        
        // The following methods are standard SAX ErrorHandler methods.
        // See SAX documentation for more info.
        
        public void warning(SAXParseException spe) throws SAXException {
            out.println("Warning: " + getParseExceptionInfo(spe));
        }
        
        public void error(SAXParseException spe) throws SAXException {
            String message = "Error: " + getParseExceptionInfo(spe);
            throw new SAXException(message);
        }
        
        public void fatalError(SAXParseException spe) throws SAXException {
            String message = "Fatal Error: " + getParseExceptionInfo(spe);
            throw new SAXException(message);
        }
    }
}
