/*
 * Copyright
 *   2009 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 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.collectivites;

import fr.gouv.finances.cp.utils.ui.VerticalFlowLayout;
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.data.DataLayerManager;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.log4j.Logger;

/**
 *
 * @author chm
 */
public class DlgSelectCollectivite extends JDialog implements ParentCollectiviteListener {
    private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);

    private DocumentModel dm;
    private XemeliosUser user;
    private JFrame parent;
    private JComboBox cbxCollectivites;
    private ParentCollectiviteContainer container;
    private boolean response;

    public DlgSelectCollectivite(DocumentModel dm, XemeliosUser user, JFrame parent) {
        super(parent, "Choisir une collectivité", true);
        this.dm=dm;
        this.user=user;
        this.parent=parent;
        initComponents();
    }

    protected void initComponents() {
        setLayout(new BorderLayout());
        JPanel vPane = new JPanel(new VerticalFlowLayout());
//        final Pair parentColls[] = new Pair[dm.getCollectivitePath().getParentsCount()];
        container = new ParentCollectiviteContainer(dm.getCollectivitePath().getParentsCount());
        JPanel collPane = new JPanel(new GridBagLayout());
        GridBagConstraints cstr = new GridBagConstraints();
        cstr.ipadx = 2;
        cstr.ipady = 2;
        cstr.insets = new Insets(2, 2, 2, 2);
        //int rowCount = 0;
        cstr.gridy=0;
        for(int i=dm.getCollectivitePath().getParentsCount()-1;i>=0;i--) {
            PnlCollectivite pnl = new PnlCollectivite(this, dm, dm.getCollectivitePath().getParent(i), container, user);
            cstr.gridx=0;
            cstr.weightx=1d;
            cstr.anchor=GridBagConstraints.EAST;
            collPane.add(pnl.getLabel(),cstr);
            cstr.gridx=1;
            cstr.weightx=0d;
            cstr.anchor=GridBagConstraints.WEST;
            collPane.add(pnl.getTextField(),cstr);
            cstr.gridx=2;
            cstr.anchor=GridBagConstraints.CENTER;
            collPane.add(pnl.getButton(),cstr);
            cstr.gridy++;
        }
        cstr.gridx=0;
        cstr.weightx=1d;
        cstr.anchor=GridBagConstraints.EAST;
        collPane.add(new JLabel("Collectivité"),cstr);
        cstr.gridx=1;
        cstr.weightx=0d;
        cstr.gridwidth=2;
        cstr.anchor=GridBagConstraints.WEST;
        cbxCollectivites = new JComboBox();
        collPane.add(cbxCollectivites,cstr);
        addComplementElements(collPane,cstr);
        vPane.add(collPane);
        JPanel hPane = new JPanel(new BorderLayout());
        JPanel buttonPane = new JPanel();
        JButton pbCancel = new JButton("Annuler");
        pbCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        buttonPane.add(pbCancel);
        JButton pbOk = new JButton("Ok");
        pbOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(cbxCollectivites.getSelectedIndex()>=0) {
                    response = true;
                    setVisible(false);
                }
            }
        });
        buttonPane.add(pbOk);
        hPane.add(buttonPane,BorderLayout.CENTER);
        vPane.add(hPane);
        add(vPane,BorderLayout.CENTER);
        container.addListener(this);
        pack();
        setLocationRelativeTo(parent);
    }
    public void addComplementElements(JPanel collPane,GridBagConstraints cstr) {
        
    }
    public void valueChanged(int pos, Pair newValue) {
        if(pos==1) { // direct parent has changed
            cbxCollectivites.removeAllItems();
            try {
                Vector<Pair> colls = DataLayerManager.getImplementation().getCollectivites(dm, container.getParents(), user);
                for(Pair p:colls)
                    cbxCollectivites.addItem(p);
            } catch(Exception ex) {
                logger.error("while querying collectivites:",ex);
            }
        } else {
            cbxCollectivites.removeAllItems();
        }
    }
    @Override
    public void setVisible(boolean b) {
        if(b) {
            response = false;
        }
        super.setVisible(b);
    }
    public boolean run() {
        setVisible(true);
        return response;
    }
    public Pair getCollectivite() { return (Pair)cbxCollectivites.getSelectedItem(); }

    public DocumentModel getDm() {
        return dm;
    }

    public XemeliosUser getUser() {
        return user;
    }
    JComboBox getCbxCollectivite() { return cbxCollectivites; }
    static class ParentCollectiviteContainer {
        Pair parentColls[];
        List<ParentCollectiviteListener> listeners;
        private int size = 0;
        public ParentCollectiviteContainer(int size) {
            super();
            this.size=size;
            parentColls = new Pair[size];
            listeners = new ArrayList<ParentCollectiviteListener>();
        }
        public void setPair(int pos,Pair value) {
            parentColls[pos] = value;
            for(int i=pos-1;i>=0;i--) {
                parentColls[i] = null;
                fireValueChanged(pos+1, value);
            }
            fireValueChanged(pos+1, value);
        }
        public Pair getPair(int pos) {
            return parentColls[pos];
        }
        protected void fireValueChanged(int pos, Pair value) {
            for(ParentCollectiviteListener listener:listeners) {
                listener.valueChanged(pos, value);
            }
        }
        void addListener(ParentCollectiviteListener listener) {
            listeners.add(listener);
        }
        public int getSize() { return size; }
        public Pair[] getParents() { return parentColls; }
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            for(int i=0;i<parentColls.length;i++) {
                sb.append(parentColls[i]);
                if(i!=(parentColls.length-1)) sb.append(",");
            }
            sb.append("]");
            return sb.toString();
        }
    }


}
