/*
Copyright (C) 2008  Dmitry Barashev

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.
*/
package net.sourceforge.ganttproject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import javax.swing.tree.TreePath;

import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;

import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.UIUtil;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.resource.ResourceNode;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.roles.RoleManager.RoleEvent;
import net.sourceforge.ganttproject.task.TaskSelectionManager;

public class ResourceTreeTable extends GPTreeTableBase {

    private final ResourceTreeTableModel myModel;
    private TableColumnExt myColName;
    private TableColumnExt myColRole;
    private TableColumnExt myColEmail;
    private TableColumnExt myColPhone;
    private TableColumnExt myColRoleForTask;
    private final RoleManager myRoleManager;

    public ResourceTreeTable(
            IGanttProject project, 
            UIFacade uifacade, 
            ResourceTreeTableModel model, 
            TaskSelectionManager taskSelectionManager, 
            CustomPropertyManager customPropertyManager) {
        super(project, uifacade, model, customPropertyManager);
        myModel = (ResourceTreeTableModel)model;
        myRoleManager = project.getRoleManager();
        myRoleManager.addRoleListener(new RoleManager.Listener() {
            public void rolesChanged(RoleEvent e) {
                onRolesChange();
            }
        });
        initTreeTable();
        createDefaultColumns();
    }

    @Override
    protected void createDefaultColumns() {
        for (ResourceTreeTableModel.DefaultColumn defaultColumn : ResourceTreeTableModel.DefaultColumn.values()) {
            TableColumnExt tableColumn = newTableColumnExt(defaultColumn.ordinal());
            tableColumn.setTitle(defaultColumn.getName());
            tableColumn.setIdentifier(defaultColumn.getID());
            addColumn(tableColumn);
            tableColumn.setVisible(defaultColumn.isDefaultVisible());
        }
        getColumnExt(ResourceTreeTableModel.DefaultColumn.ROLE.getID()).setCellEditor(createRoleEditor());
        getColumnExt(ResourceTreeTableModel.DefaultColumn.ROLE_IN_TASK.getID()).setCellEditor(createRoleEditor());
    }

    @Override
    protected void initTreeTable() {
        super.initTreeTable();
        ImageIcon icon = new ImageIcon(getClass().getResource("/icons/simple_task.gif"));
        setOpenIcon(icon);
        setClosedIcon(icon);
    }

    private TableCellEditor createRoleEditor() {
        JComboBox comboBox = new JComboBox(getRoleManager().getEnabledRoles());
        comboBox.setEditable(false);
        return new DefaultCellEditor(comboBox);
    }

    private RoleManager getRoleManager() {
        return myRoleManager;
    }
    private void onRolesChange() {
        TableColumnExt roleColumn = getColumnExt(ResourceTreeTableModel.DefaultColumn.ROLE.getID());
        if (roleColumn!=null) {
            roleColumn.setCellEditor(createRoleEditor());
        }
        TableColumnExt roleInTaskColumn = getColumnExt(ResourceTreeTableModel.DefaultColumn.ROLE_IN_TASK.getID());
        if (roleInTaskColumn!=null) {
            roleInTaskColumn.setCellEditor(createRoleEditor());
        }
    }

    @Override
    protected void addNewCustomColumn(CustomPropertyDefinition customPropertyDefinition) {
        super.addNewCustomColumn(customPropertyDefinition);
        myModel.addCustomColumn(customPropertyDefinition);
    }

    @Override
    protected void deleteCustomColumn(CustomPropertyDefinition customPropertyDefinition) {
        super.deleteCustomColumn(customPropertyDefinition);
        myModel.deleteCustomColumn(customPropertyDefinition);
    }

    /** @return the list of the selected nodes. */
    List<DefaultMutableTreeTableNode> getSelectedNodes() {
        TreePath[] currentSelection = getTree().getSelectionPaths();

        if (currentSelection == null || currentSelection.length == 0) {
            return Collections.emptyList();
        }
        ArrayList<DefaultMutableTreeTableNode> result = new ArrayList<DefaultMutableTreeTableNode>();
        for (TreePath path : currentSelection) {
            result.add((DefaultMutableTreeTableNode)path.getLastPathComponent());
        }
        return result;
    }

    boolean isExpanded(ProjectResource pr) {
        ResourceNode node = myModel.exists(pr);
        return node==null ? false : getTreeTable().isExpanded(new TreePath(node.getPath()));
    }
    
    private void moveResource(int offset) {
        List<DefaultMutableTreeTableNode> selectedNodes = getSelectedNodes();
        if(selectedNodes.size()!=1) {
            return;
        }        
        DefaultMutableTreeTableNode selectedNode = selectedNodes.get(0);
        if (selectedNode instanceof ResourceNode) {
            HumanResource hr = (HumanResource) selectedNode.getUserObject();
            int index = selectedNode.getParent().getIndex(selectedNode);
            if (index+offset>=0 && index+offset<selectedNode.getParent().getChildCount()) {
                if (offset < 0) {
                    getProject().getHumanResourceManager().up(hr);  
                }
                else {
                    getProject().getHumanResourceManager().down(hr);
                }
                UIUtil.moveTreeNode(selectedNode, (DefaultMutableTreeTableNode) selectedNode.getParent(), index+offset, getTree(), myModel);
            }
        }
    }
    void upResource() {
        moveResource(-1);
    }
    /** Move down the selected resource */
    void downResource() {
        moveResource(1);
    }

}
