/*
 * 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.
 */

/*
 * CCDynamicTreeDescriptor.java
 *
 * Created on April 8, 2004, 1:25 PM
 */

package com.sun.enterprise.tools.guiframework.view.descriptors;

import java.util.ArrayList;
import java.util.List;
import com.iplanet.jato.ModelManager;
import com.iplanet.jato.RequestManager;
import com.iplanet.jato.RequestContext;
import com.iplanet.jato.view.ContainerView;
import com.iplanet.jato.view.ContainerViewBase;
import com.iplanet.jato.view.View;

import com.sun.web.ui.model.CCTreeModel;
import com.sun.web.ui.model.CCTreeModelInterface;
import com.sun.web.ui.model.CCNavNode;

import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
import com.sun.enterprise.tools.guiframework.view.DescriptorCCDynamicTree;
//import com.sun.enterprise.tools.admingui.tree.BasicTree;

/**
 *
 * @author  anilam
 */
public class CCDynamicTreeDescriptor extends ViewDescriptor {
    
    
    /** Creates a new instance of CCDynamicTreeDescriptor */
    public CCDynamicTreeDescriptor(String name) {
        super(name);
        //System.out.println("!!!!!!!!!!! CCDynamicTreeDescriptor constructor ");
    }
    
    /**
     *	This is a factory method for IndexTreeView instances.
     *
     *	@param	ctx		The RequestContext
     *	@param	container	The container of the new IndexTreeView
     *	@param	name		The IndexTreeView name
     */
    public View getInstance(RequestContext ctx, ContainerView container, String name) {
        //System.out.println("!!!!!!!!!!! getInstance ");
        CCTreeModelInterface model = getModel(ctx,  (String)getParameter("treeIteratorClass"), container);
        return new DescriptorCCDynamicTree(ctx, container, name, this, model);
    }
    
     public CCTreeModelInterface getModel(RequestContext ctx, String treeIteratorClassName, ContainerView container) {
	// Determine if the session should be used w/ the model manager.
	boolean fromSession = shouldGetModelFromSession();
	boolean toSession = shouldPutModelToSession();
	String instanceName = getModelInstanceName();
        //System.out.println("!!!!!!!!!!! getModel");
	// Use the ModelManager to create/get the model
        // This is specified in admingui/ModelTypeMapImpl
	ModelManager mgr = RequestManager.getRequestContext().getModelManager();
	CCTreeModel model = (CCTreeModel)mgr.getModel(
		CCTreeModelInterface.class,
		instanceName, fromSession, toSession);
        
        //The model returned by the model manager is the same instance for every request.
        //We should check if this has already been initialized and set up already before
        //we try to initialize it.
        
        List list = model.getNodes();
        //System.out.println("!!!!!!!!!!!!!getNodes");
        if (list ==null || list.size() ==0) {
            //System.out.println("!!!!!!!!!!!!! node list size is EMPTY");
            try{
                Class cls = Class.forName(treeIteratorClassName);
                BasicTree obj = (BasicTree) cls.newInstance();
                obj.init(this, ctx);
                //Create the root node
                Object root = obj.getRoot();
                String displayName = obj.getDisplayName(root);
                CCNavNode rootNode = new CCNavNode(0, displayName, "", "");
                rootNode.setAsRoot();
                rootNode.setValue(obj.getURL()+obj.getKey(null));
                model.addNode(rootNode);
                createSubTree(obj, root, rootNode, 1);
            }catch (ClassNotFoundException ex){
                throw new FrameworkException(
                "Cannot find the class " + treeIteratorClassName + " specified by the param 'modelClass'",
                ex, this, container);
            }catch(Exception ex1){
                throw new FrameworkException("Cannot build the tree model ", ex1, this, container);
            }
        }
        //System.out.println("!!!!!!!!!!!!! getModel returns");
        return model;
     }
     
     
     private int createSubTree(BasicTree obj, Object parent, CCNavNode parentNode, int id){
         
         if (!obj.hasChildren(parent)){
             parentNode.setAcceptsChildren(false);
             return id;
         }
         ArrayList list = obj.getChildren(parent);
         for(int i=0; i<list.size(); i++){
             Object data = list.get(i);
             String nm = obj.getDisplayName(data);
            //System.out.println("XXXX call CCNavNode id= " + id + " nm=" +nm) ;
             CCNavNode node = new CCNavNode(id++, nm, "", "");
            //System.out.println("after creating CCNavNode");
            node.setValue(obj.getURL()+obj.getKey(data));
             //System.out.println(nm + ": Value set to " + node.getValue());
             parentNode.addChild(node);
             id = createSubTree(obj, data, node, id);
         }
         //System.out.println("====== CreateSubTree returns =========");
         return id;
     }
}
