/**
 * Dialog with options for filters.
 * 
 * Created 12.2007
 * 
 * @author Joanna Muras 
 */
package net.sourceforge.ganttproject.datafilter;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JPanel;

import net.sourceforge.ganttproject.action.CancelAction;
import net.sourceforge.ganttproject.action.GPAction;
import net.sourceforge.ganttproject.action.OkAction;
import net.sourceforge.ganttproject.datafilter.task.FilteredTasks;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.options.OptionsPageBuilder;
import net.sourceforge.ganttproject.gui.options.model.GPOptionGroup;


public class FilterOptionsDialogAction extends GPAction {

    private final UIFacade myUIFacade;
    private GPOptionGroup[] myGroups;

    public FilterOptionsDialogAction(UIFacade uifacade) {
        super("datafilter.filterOptions");
        myUIFacade = uifacade;
    }

    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < myGroups.length; i++) {
            myGroups[i].lock();
        }
        final OkAction okAction = new OkAction() {
            public void actionPerformed(ActionEvent e) {
                commit();
            }
        };
        final CancelAction cancelAction = new CancelAction() {
            public void actionPerformed(ActionEvent e) {
                rollback();
            }
        };
        myUIFacade.showDialog(createDialogComponent(), new Action[] { okAction,
            cancelAction });
    }

    private void commit() {
        for (int i = 0; i < myGroups.length; i++) {
            myGroups[i].commit();
        }
    }

    private void rollback() {
        for (int i = 0; i < myGroups.length; i++) {
            myGroups[i].rollback();
        }
    }

    private Component createDialogComponent() {
        OptionsPageBuilder builder = new OptionsPageBuilder();
        JPanel combinedPanel = new JPanel(new BorderLayout());
        JComponent comp = builder.buildPlanePage(myGroups);
        combinedPanel.add(comp, BorderLayout.CENTER);
        combinedPanel.setBorder(BorderFactory.createEmptyBorder(0,0,3,0));
        return combinedPanel;
    }

    @Override
    protected String getIconFilePrefix() {
        return null;
    }

    @Override
    protected String getLocalizedName() {
        return getI18n("datafilter.filterSettings");
    }

    public void setFilter(FilteredTasks newFilter) {
        myGroups = newFilter.getSettings();
        if (myGroups==null || myGroups.length==0) {
            setEnabled(false);
        }
        else {
            setEnabled(true);
        }
    }


}
