/*
 * Copyright
 *   2005 axYus - www.axyus.com
 *   2005 Y.Laurelut - yann.laurelut@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS 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.
 *
 * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.cp.xemelios.ui.importDialog;

import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import org.apache.log4j.Logger;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;

/**
 * Model for the TreeTable used in the ImportDialog.
 * 
 *  @author Yann Laurelut
 */
public class ImportFileTreeTableModel extends DefaultTreeTableModel {
    private static final Logger logger = Logger.getLogger(ImportFileTreeTableModel.class);

	/** Constants for the columns indices */
	private final static int NOM_FICHIER = 0;
	private final static int A_IMPORTER = 1;
	
	public ImportFileTreeTableModel(TreeNode node) {
		super(node);
	}

	public int getColumnCount() {
		return 2;
	}
	
	@Override
	public Class getColumnClass(int column) {
		if(column==A_IMPORTER) {
			return Boolean.class;
		}
		else return super.getColumnClass(column);
	}

	/**
	 * Returns which object is displayed in this column.
	 */
	public Object getValueAt(Object node, int column) {
		Object result = null;
		if (node instanceof DefaultMutableTreeNode) {
			DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
			if (defNode.getUserObject() instanceof ImportFile) {
				ImportFile fichier = (ImportFile) defNode.getUserObject();
				switch (column) {
				case NOM_FICHIER:
                                        result = fichier.getName();
					break;
				case A_IMPORTER:
					result = new Boolean(fichier.isToBeImported());
					break;
				}
			}
		}
		return result;
	}
	
	/**
	 * What the TableHeader displays when the Table is in a JScrollPane.
	 */
	public String getColumnName(int column) {
		String res = "";
		switch (column) {
		case NOM_FICHIER:
			res = "Nom de fichier";
			break;
		case A_IMPORTER:
			res = "Importer";
			break;
		}
		return res;
	}

	/**
	 * Tells if a column can be edited.
	 */
	public boolean isCellEditable(Object node, int column) {
		if(column==A_IMPORTER) return true;
		else return false;
	}

	/**
	 * Called when done editing a cell.
	 */
	public void setValueAt(Object value, Object node, int column) {
		if (node instanceof DefaultMutableTreeNode) {
			DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
			if (defNode.getUserObject() instanceof ImportFile) {
				ImportFile fichier = (ImportFile) defNode.getUserObject();
				switch (column) {
				case NOM_FICHIER:	// should never happen in our case
					break;
				case A_IMPORTER:
					boolean valeur = ((Boolean)value).booleanValue();
					// on coche la case pour le fichier ou répertoire cliqué
					((ImportFile)defNode.getUserObject()).setToBeImported(valeur);
					// si c'est pour cocher, on propage au dessus
					if(valeur) propagateCheckValueAbove(valeur, defNode);
					// dans le cas d'un répertoire, on propage aussi vers le bas
					if(!fichier.isFile()) {
						propagateCheckValueBelow(valeur, defNode);
					}
					nodesChanged((DefaultMutableTreeNode)getRoot(), null);
					break;
				}
			}
		}
	}
	
	/**
	 * Sets the value of the checkbox to all the nodes above
	 * the given one, up to the root.
	 * @param value To know if this node needs to be imported
	 * @param node The starting node
	 */
	private void propagateCheckValueAbove(boolean value, DefaultMutableTreeNode node) {
		((ImportFile)node.getUserObject()).setToBeImported(value);
		if(node.getParent()!=null) {
			propagateCheckValueAbove(value, (DefaultMutableTreeNode)node.getParent());
		}
	}
	
	/**
	 * Sets the value of the checkbox to all the nodes below
	 * the given one, every child recursively.
	 * @param value To know if this node needs to be imported
	 * @param node The starting node
	 */
	private void propagateCheckValueBelow(boolean value, DefaultMutableTreeNode node) {
		((ImportFile)node.getUserObject()).setToBeImported(value);
		if(node.getChildCount()>0) {
			for(Enumeration enumerator = node.children(); enumerator.hasMoreElements(); ) {
				DefaultMutableTreeNode child = (DefaultMutableTreeNode)enumerator.nextElement();
				propagateCheckValueBelow(value, child);
			}
		}
	}
	
	/**
	 * Returns the list of the file to export.
	 * @return A List of files to export
	 */
	public List<ImportFile> getFilesToImportList() {
		List<ImportFile> result = new Vector<ImportFile>();
		
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.getRoot();
		for(Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements(); ) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumerator.nextElement();
			ImportFile f = (ImportFile)node.getUserObject();
			if(f.isFile() && f.isToBeImported()) {
				result.add(f);
			}
		}
		
		return result;
	}
	
	/**
	 * Selects all the files and directories for import
	 */
	public void selectAll() {
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.getRoot();
		for(Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements(); ) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumerator.nextElement();
			ImportFile f = (ImportFile)node.getUserObject();
			f.setToBeImported(true);
		}
		nodesChanged(root, null);
	}
	
	/**
	 * Uncheck each entry, removing them
	 * from the import list
	 */
	public void selectNone() {
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.getRoot();
		for(Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements(); ) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumerator.nextElement();
			ImportFile f = (ImportFile)node.getUserObject();
			f.setToBeImported(false);
		}
		nodesChanged(root, null);
	}
        
        public boolean isLeaf(TreeNode node) {
            boolean ret = super.isLeaf(node);
            logger.debug("isLeaf("+node+") -> "+ret);
            return ret;
        }
}
