/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 C.Marchand - christophe.marchand@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 Lesser General Public License as published by
 * the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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.collectivites;

import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.SpecialKeyEntryModel;
import fr.gouv.finances.dgfip.xemelios.common.config.SpecialKeyModel;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import java.awt.GridBagConstraints;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.log4j.Logger;

/**
 *
 * @author chm
 */
public class DlgSelectNavigationTarget extends DlgSelectCollectivite {
    private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);
    ArrayList<JComboBox> specialKeysLists;
    ArrayList<SpecialKeyModel> models;
    ArrayList<Pair> specialKeys;
    private JComboBox cbxBudget;

    public DlgSelectNavigationTarget(DocumentModel dm, XemeliosUser user, JFrame parent) {
        super(dm,user,parent);
        setTitle("Choisir une collectivité, un budget ...");
    }
    public Pair getBudget() { return (Pair)cbxBudget.getSelectedItem(); }
    public List<Pair> getSpecialKeys() { return specialKeys; }

    @Override
    public void addComplementElements(JPanel collPane, GridBagConstraints cstr) {
        getCbxCollectivite().addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.DESELECTED) {
                    cbxBudget.removeAllItems();
                } else {
                    try {
                        Vector<Pair> data = DataLayerManager.getImplementation().getBudgets(getDm(), getCollectivite(), getUser());
                        for(Pair p:data) cbxBudget.addItem(p);
                        cbxBudget.setSelectedIndex(0);
                    } catch(Exception ex) {
                        logger.error("while getting budgets:",ex);
                    }
                }
            }
        });
        cstr.gridy++;
        cstr.gridx=0;
        cstr.gridwidth=1;
        cstr.weightx=1d;
        cstr.anchor=GridBagConstraints.EAST;
        collPane.add(new JLabel("Budget"),cstr);
        cbxBudget = new JComboBox();
        cstr.gridx=1;
        cstr.weightx=0d;
        cstr.gridwidth=2;
        cstr.anchor=GridBagConstraints.WEST;
        collPane.add(cbxBudget,cstr);
        if(!getDm().getSpecialKeys().isEmpty()) {
            cbxBudget.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    try {
                        Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys1(getDm(), getCollectivite(), getBudget(), true, getUser());
                        JComboBox cbx = specialKeysLists.get(0);
                        for(Pair p:data) cbx.addItem(p);
                        cbx.setSelectedIndex(0);
                    } catch(Exception ex) {
                        logger.error("while getting keys1:",ex);
                    }
                }
            });
            specialKeysLists = new ArrayList<JComboBox>();
            models = new ArrayList<SpecialKeyModel>();
            specialKeys = new ArrayList<Pair>();
            for(SpecialKeyModel skm:getDm().getSpecialKeys()) {
                cstr.gridy++;
                cstr.gridx=0;
                cstr.gridwidth=1;
                cstr.weightx=1d;
                cstr.anchor=GridBagConstraints.EAST;
                collPane.add(new JLabel(skm.getLibelle()),cstr);
                JComboBox cbx = new JComboBox();
                cstr.gridx=1;
                cstr.weightx=0d;
                cstr.gridwidth=2;
                cstr.anchor=GridBagConstraints.WEST;
                collPane.add(cbx,cstr);
                specialKeysLists.add(cbx);
                cbx.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent e) {
                        JComboBox thisOne = (JComboBox)e.getItemSelectable();
                        int rank = specialKeysLists.indexOf(thisOne);
                        if(e.getStateChange()==ItemEvent.DESELECTED) {
                            for(int i=rank+1;i<specialKeysLists.size();i++) {
                                JComboBox cbx = specialKeysLists.get(i);
                                cbx.removeAllItems();
                            }
                            while(specialKeys.size()>rank) specialKeys.remove(rank);
                        } else {
                            specialKeys.add((Pair)thisOne.getSelectedItem());
//                            SpecialKeyModel skm = models.get(rank);
                            if(rank==0) {
                                try {
                                    Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys2(getDm(), getCollectivite(), getBudget(), (Pair)thisOne.getSelectedItem(), true, getUser());
                                    JComboBox cbx = specialKeysLists.get(1);
                                    for(Pair p:data) cbx.addItem(p);
                                    cbx.setSelectedIndex(0);
                                } catch(IndexOutOfBoundsException aioobEx) {
                                    // ignore
                                } catch(Exception ex) {
                                    logger.error("while getting keys2:",ex);
                                }
                            } else if(rank==1) {
                                JComboBox previousOne = specialKeysLists.get(0);
                                try {
                                    Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys3(getDm(), getCollectivite(), getBudget(), (Pair)thisOne.getSelectedItem(), (Pair)previousOne.getSelectedItem(),true, getUser());
                                    JComboBox cbx = specialKeysLists.get(2);
                                    for(Pair p:data) cbx.addItem(p);
                                    cbx.setSelectedIndex(0);
                                } catch(IndexOutOfBoundsException aioobEx) {
                                    // ignore
                                } catch(Exception ex) {
                                    logger.error("while getting keys3:",ex);
                                }
                            }
                        }
                    }
                });
            }
        }
    }

}
