/**
 *############################################################################
 * A component of the Greenstone Librarian Interface, part of the Greenstone
 * digital library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Author: Michael Dewsnip, NZDL Project, University of Waikato, NZ
 *
 * Copyright (C) 2004 New Zealand Digital Library Project
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *############################################################################
 */

package org.greenstone.gatherer.file;


import java.io.*;
import java.util.*;
import javax.swing.filechooser.FileSystemView;
import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.collection.BasicCollectionConfiguration;  // !!! Don't like this here
import org.greenstone.gatherer.collection.CollectionManager;  // !!! Don't like this here
import org.greenstone.gatherer.util.ArrayTools;
import org.greenstone.gatherer.util.StaticStrings;
import org.greenstone.gatherer.util.Utility;


/** This class represents one node in the workspace tree. */
public class WorkspaceTreeNode
    extends FileNode
{
    private boolean is_gs3_site_node = false;
    private boolean is_group_node = false;
    private boolean is_in_loaded_collection = false;
  private boolean is_in_coll_all_files_mode = false;
    private String title = null;


    public WorkspaceTreeNode(File file)
    {
	super(file);
    }


    public WorkspaceTreeNode(File file, String title)
    {
	this(file);
	this.title = title;
    }
  public WorkspaceTreeNode(File file, String title, int mode)
    {
	this(file);
	this.title = title;
        if (mode == Utility.FILES_MODE) {
          this.is_in_coll_all_files_mode = true;
        }
    }


    public FileNode addChildNode(File file)
    {
	WorkspaceTreeNode child_node = new WorkspaceTreeNode(file);
	child_node.setModel(model);
	child_node.setParent(this);
	return child_node;
    }


    /** Is this file node within the currently loaded collection? */
    public boolean isInLoadedCollection()
    {
	if (is_in_loaded_collection) {
	    return true;
	}
	else {
	    FileNode parent = (FileNode) getParent();
	    if (parent != null) {
		return parent.isInLoadedCollection();
	    }
	}
	return false;
    }


    public boolean isReadOnly()
    {
	// The workspace tree is read only
	return true;
    }


    public void map()
    {
	// Special Case: "Documents in Greenstone Collections" -- map the collections installed in Greenstone
	if (file == null) { // a special mapping folder
	    if (child_nodes != null) {
		// don't bother mapping again if we already have children
		return;
	    }
	    child_nodes = new ArrayList();
	    if ((title.equals(Dictionary.get("Tree.World")) || title.equals(Dictionary.get("Tree.CollFiles")) ) && Gatherer.GS3) {
		// the Greenstone collections folder for GS3 - this contains a 
		// folder for each site

		File start = new File(Utility.getSitesDir(Configuration.gsdl3_web_path));
		File sites[] = start.listFiles();
		ArrayTools.sort(sites);
		for (int i = 0; sites != null && i < sites.length; i++) {
		    File collect_dir = new File(sites[i], "collect");
		    if (!collect_dir.exists()) {
			continue;
		    }
                    if (!is_in_coll_all_files_mode && sites[i].getName().equals(StaticStrings.MODEL_SITE_NAME)) {
                      // import view hides modelsite, but files view doesn't
                      continue;
                    }
		    WorkspaceTreeNode child = new WorkspaceTreeNode(null, sites[i].getName());
		    child.is_gs3_site_node = true;
                    child.is_in_coll_all_files_mode = this.is_in_coll_all_files_mode;
		    child.unmap();
		    child.setModel(model);
		    child.setParent(this);
		    child.map();
		    child_nodes.add(child);
		}
		model.nodeStructureChanged(this);
		
	    } else if (title.equals(Dictionary.get("Tree.World")) || title.equals(Dictionary.get("Tree.CollFiles")) || is_gs3_site_node || is_group_node) {
		// For each of the children directories, which are collections...
		File start;
		if (is_gs3_site_node ) {
		    start = new File(Gatherer.getSitesDirectoryPath() + title + File.separator + "collect" + File.separator);
		} 
		else if (is_group_node) {
		  start = new File(Gatherer.getCollectDirectoryPath() + title);
		}
		else {
		    start = new File(Gatherer.getCollectDirectoryPath());
		}
		File cols[] = start.listFiles();
		ArrayTools.sort(cols);

		// We add their import directories, except for the model collection
		for (int i = 0; cols != null && i < cols.length; i++) {
		    if (is_in_coll_all_files_mode || !cols[i].getName().equals(StaticStrings.MODEL_COLLECTION_NAME)) {
			// check for groups
			String file_name = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
			BasicCollectionConfiguration collect_cfg = new BasicCollectionConfiguration(new File(cols[i], file_name));
			if (collect_cfg.getCollectGroup().equals("true")) {
			  WorkspaceTreeNode child = new WorkspaceTreeNode(null, cols[i].getName());
			  child.is_group_node = true;
			  child.unmap();
			  child.setModel(model);
			  child.setParent(this);
			  child.map();
			  child_nodes.add(child);
			} else {
                          File coll_dir;
                          if (is_in_coll_all_files_mode == true) {
                            coll_dir = cols[i];
                          } else {
                            coll_dir = new File(cols[i], "import");
                            if (!coll_dir.exists()) {
                              continue;
                            }
                          }
//			  File import_dir = new File(cols[i], "import");
//			  if (!import_dir.exists()) {
//			    continue;
//			  }
			  
			  WorkspaceTreeNode collection_root = new WorkspaceTreeNode(coll_dir, collect_cfg.toString());
			  collection_root.setParent(this);
			  collection_root.setModel(model);
			  
			  // One last piece of magic so we can determine the current collection
			  // Now made to work with collection groups
			  String groupQualifiedColName = cols[i].getName();
			  if(is_group_node) { // then title would have stored the colgroup name
			      groupQualifiedColName = title + File.separator + cols[i].getName();
			  }
			  collection_root.is_in_loaded_collection = groupQualifiedColName.equals(CollectionManager.getLoadedCollectionName());
			  child_nodes.add(collection_root);
			}
		    }
		}
		model.nodeStructureChanged(this);
	    }
	    else if (title.equals(Dictionary.get("Tree.Root"))) {
		// Special Case: "Local Filespace" on Windows -- create a node for each filesystem root (drive letter)
		
		// Sort the roots into alphabetical order
		File[] roots = File.listRoots();
		ArrayTools.sort(roots);
		for (int i = 0; i < roots.length; i++) {
		    // Only add root if it isn't a floppy drive
		    // this used to cause problems, I don't think it does now...
		    //if (!FileSystemView.getFileSystemView().isFloppyDrive(roots[i])) {
		    child_nodes.add(addChildNode(roots[i]));
			// }
		}
	    }
	} // if file == null
	
	// General case
	else {
	    super.map();
	}
    }


    public String toString()
    {
	if (title != null) {
	    return title;
	}

	return super.toString();
    }

}
