package usda.weru.remoteDataAccess.csip;

import usda.weru.remoteDataAccess.RdaHierarchicalItem;
import usda.weru.remoteDataAccess.RdaInputController;

/**
 *
 * @author mhaas
 */
public class CsipHierarchicalItem extends RdaHierarchicalItem {

    public CsipHierarchicalItem(String name, RdaInputController controller) {
        super(name, controller);
    }

    public CsipHierarchicalItem(String name, RdaHierarchicalItem parent) {
        super(name, parent);
    }
    
    @Override
    public void finalize () throws Throwable {
        super.finalize();
    }
    
    //
    // This is the basic method for adding children into the hierarchical list of items.
    // Some services just give a list of files with thier entire ancestor path.  So those items can be added in as they are served
    // Other services are built hierarchically from the root, with a new call to get the children of each node.
    //
    // Adds a whole path into this item
    // the path can be just one file name, and that file will get added as a child.
    // the path can have parents and a file.  In this case the parents will be searched for in this existing item's parent list
    //     If the parent item is found, it is used, if not, it is added into the tree.
    //
    public void addPath (String path) {
        RdaHierarchicalItem subTree;
        CsipHierarchicalItem newItem;

        int strIdx1 = 0;
        int strIdx2;
        int i;


        // Some of the LMOD man data has "/" in the names,
        // not as a path separator but as a lexical elment of the name...
        // This seems to work initially:
        // Make a temp substitution, before breaking the path into components (below)
        // then substitute back in the individual filename element.
        path = path.replace("/", "MMMEEEHHHPLACEHOLDER");

        subTree = this;
        while (strIdx1 < path.length()) {
            //Note: this parentPath separator is NOT O.S. related
            //      it is 'hard coded' into the data in the database in Lmod
            path = path.replace('\\', '/');
            
            if ((strIdx2 = path.indexOf('/', strIdx1)) == -1) {
                strIdx2 = path.length();
            }
            //subTreeChildren = subTree.getChildren();
            String pathItemName = path.substring(strIdx1, strIdx2);
            
            // Substitute back.  See above.
            pathItemName = pathItemName.replace("MMMEEEHHHPLACEHOLDER", "/");
            
            newItem = new CsipHierarchicalItem (pathItemName, subTree);
            if ((i = subTree.findChild(newItem)) == -1) {
                i = subTree.addChild(newItem) - 1;
            }
            subTree = subTree.getChild(i);
            strIdx1 = strIdx2+1;
        }
    }
    
}
