package net.sourceforge.ganttproject;

import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.table.TableColumn;

import org.jdesktop.swingx.table.TableColumnExt;

import net.sourceforge.ganttproject.action.CancelAction;
import net.sourceforge.ganttproject.action.OkAction;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.options.OptionsPageBuilder;
import net.sourceforge.ganttproject.gui.options.model.BooleanOption;
import net.sourceforge.ganttproject.gui.options.model.DefaultBooleanOption;

public class ShowHideColumnsDialog {

    public class ShowHideColumnOption extends DefaultBooleanOption {
        private TableColumnExt myColumn;

        public ShowHideColumnOption(String id, TableColumnExt column) {
            super(id, column.isVisible());
            myColumn = column;
        }
        public void commit() {
            super.commit();
            if (isChecked() && !myColumn.isVisible()) {
                myColumn.setVisible(true);
            }
            if (!isChecked() && myColumn.isVisible()) {
                myColumn.setVisible(false);
            }
        }

    }

    private final UIFacade myUIfacade;
    private final List<TableColumn> myColumns;

    public ShowHideColumnsDialog(UIFacade facade, List<TableColumn> columns) {
        myUIfacade = facade;
        myColumns = columns;
    }

    public void show() {
        final BooleanOption[] options = new BooleanOption[myColumns.size()];
        int index = 0;
        for (TableColumn nextColumn : myColumns) {
            TableColumnExt column = (TableColumnExt) nextColumn;
            BooleanOption nextOption = new ShowHideColumnOption(
                    "<html><p width=200px>"+String.valueOf(column.getHeaderValue()), 
                    column);
            nextOption.lock();
            options[index++] = nextOption;
        }
        JComponent listComponent = new OptionsPageBuilder().createScrollableList(options, 16);
        OkAction okAction = new OkAction() {
            public void actionPerformed(ActionEvent e) {
                for (int i=0; i<options.length; i++) {
                    options[i].commit();
                }
            }
        };
        CancelAction cancelAction = new CancelAction() {
            public void actionPerformed(ActionEvent e) {
                for (int i=0; i<options.length; i++) {
                    options[i].rollback();
                }
            }           
        };
        listComponent.setBorder(new CompoundBorder(new EmptyBorder(3,3,5,3), new EtchedBorder()));
        myUIfacade.showDialog(listComponent, new Action[] {okAction, cancelAction});
    }

}