/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 N.Le Corre - nicolas.lecorre@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;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;

import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import fr.gouv.finances.cp.utils.Pair;
import fr.gouv.finances.cp.xemelios.common.config.DocumentModel;
import fr.gouv.finances.cp.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;

@SuppressWarnings("serial")
public class DlgExportAll extends DlgChooseDocuments {
    private static Logger logger = Logger.getLogger(DlgCleanDatabaseOld.class);
    private Action escapeAction;
    
    public DlgExportAll(java.awt.Frame parent, boolean modal, DocumentsModel _dm) {
        super(parent, modal, _dm, false);
        setTitle("Exporter");
        setBActionLibelle("Exporter");
        ((PanelChooseDatabaseFichier)getJTabbedPane1().getComponent(1)).setMode(PanelChooseDatabaseFichier.MODE_EXPORT);
    }
    
    @Override
    protected void doAction(ActionEvent evt) {
        if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
            export(((PanelChooseDatabaseDonnees)getJTabbedPane1().getSelectedComponent()).getJTree1().getSelectionPath());
        }
        if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
            exportFichiers();
        }
    }
    
    /**
     * EXPORT PAR FICHIER
     */
    protected void exportFichiers() {
        DatabaseTreeDataFichier.Data datas =  ((PanelChooseDatabaseFichier)getJTabbedPane1().getSelectedComponent()).getData().getData();
        for (DatabaseTreeDataFichier.Data d:datas.getChilds()) {
            exportData(d);
        }
    }
    
    protected void exportData(DatabaseTreeDataFichier.Data datas) {
        // Si l'on veux exorter ce niveau
        if (datas.isSelected()) {
            doExportData(datas);
        } else {
            for (DatabaseTreeDataFichier.Data d:datas.getChilds()) {
                exportData(d);
            }
        }
    }
    
    public void doExportData(DatabaseTreeDataFichier.Data d) {
        DocumentModel dm = null;
        Pair collectivite = null;
        Pair budget = null;
        String fichier = null;
        
        // export selon le niveau
        switch (d.getLevel()) {
            case DatabaseTreeDataFichier.Data.LVL_BUD : {
                StringTokenizer st = new StringTokenizer(d.getKey(), "|");
                dm = getDm().getDocumentById(st.nextToken());
                collectivite = new Pair(st.nextToken(), "");
                budget = new Pair(st.nextToken(), "");
                logger.debug("exporting BUD : "+dm.getId()+", "+collectivite.key+", "+budget.key);
                break;
            }
            case DatabaseTreeDataFichier.Data.LVL_FIC : {
                StringTokenizer st = new StringTokenizer(d.getKey(), "|");
                dm = getDm().getDocumentById(st.nextToken());
                collectivite = new Pair(st.nextToken(), "");
                budget = new Pair(st.nextToken(), "");
                fichier = st.nextToken();
                logger.debug("exporting FIC : "+dm.getId()+", "+collectivite.key+", "+budget.key+", "+fichier);
                break;
            }
        }
        
        if (d.getLevel()==DatabaseTreeDataFichier.Data.LVL_BUD || d.getLevel()==DatabaseTreeDataFichier.Data.LVL_FIC) {
            if(JOptionPane.showConfirmDialog(this,"Etes-vous sur de vouloir exporter ces informations ?\n\nCette op�ration peut prendre beaucoup de temps\nsi le nombre d'�l�ments � exporter est important.","Export",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
                
                DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.TAG);
                try { dmsTmp.addChild(dm, DocumentModel.TAG); } catch (Throwable t) {}
                
                DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_CONF);
                sc.setDm(dm);
                sc.setColl(collectivite);
                sc.setBudg(budget);
                sc.setFic(fichier);
                sc.setWhatToExport(d.getLevel());
                sc.setVisible(true);
            }
        }
    }
    
    /**
     * EXPORT PAR DONNEES
     */
    
    /**
     * Exporte a partir du chemin specifie
     * @param tp Le chemin a exporter
     * @return <tt>true</tt> s'il faut rafraichir l'arbre
     */
    protected void export(TreePath tp) {
        if(tp==null) return;
        DatabaseTreeDataDonnee.DataNode node = (DatabaseTreeDataDonnee.DataNode)tp.getLastPathComponent();
        export(node);
    }
    /**
     * Exporte a partir du noeud specifie
     * @param dn
     * @return <tt>true</tt> s'il faut rafraichir l'arbre
     */
    protected void export(DatabaseTreeDataDonnee.DataNode dn) {
        DocumentModel dm = null;
        Pair collectivite = null;
        Pair budget = null;
        String fichier = null;
        Pair perso1 = null;
        Pair perso2 = null;
        
        int level = dn.getType();
        switch(level) {
            case DatabaseTreeDataDonnee.DataNode.TYPE_BUDGET: {
                budget = (Pair)dn.getData();
                collectivite = (Pair)dn.getParent().getData();
                dm = (DocumentModel)(dn.getParent().getParent().getData());
                break;
            }
            case DatabaseTreeDataDonnee.DataNode.TYPE_PERSO1: {
                perso1 = (Pair)dn.getData();
                budget = (Pair)dn.getParent().getData();
                collectivite = (Pair)dn.getParent().getParent().getData();
                dm = (DocumentModel)(dn.getParent().getParent().getParent().getData());
                break;
            }
            case DatabaseTreeDataDonnee.DataNode.TYPE_PERSO2: {
                perso2 = (Pair)dn.getData();
                perso1 = (Pair)dn.getParent().getData();
                budget = (Pair)dn.getParent().getParent().getData();
                collectivite = (Pair)dn.getParent().getParent().getParent().getData();
                dm = (DocumentModel)(dn.getParent().getParent().getParent().getParent().getData());
            }
        }
        
        if (level==DatabaseTreeDataDonnee.DataNode.TYPE_BUDGET || level==DatabaseTreeDataDonnee.DataNode.TYPE_PERSO1 || level==DatabaseTreeDataDonnee.DataNode.TYPE_PERSO2) {
            if(JOptionPane.showConfirmDialog(this,"Etes-vous sur de vouloir exporter ces informations ?\n\nCette op�ration peut prendre beaucoup de temps\nsi le nombre d'�l�ments � exporter est important.","Export",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
                
                DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.TAG);
                try { dmsTmp.addChild(dm, DocumentModel.TAG); } catch (Throwable t) {}
                
                DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU);
                sc.setDm(dm);
                sc.setColl(collectivite);
                sc.setBudg(budget);
                sc.setFic(fichier);
                sc.setSK1(perso1);
                sc.setSK2(perso2);
                sc.setWhatToExport(level);
                sc.setVisible(true);
            }
        }
    }
    @Override
    protected JRootPane createRootPane() {
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        JRootPane rp = new JRootPane();
        escapeAction = new AbstractAction("Fermer") {
            /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;
            
            public void actionPerformed(ActionEvent evt) {
                setVisible(false);
            }
        };
        rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rp;
    }
}
