/*
 * 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 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;

import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
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.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.dgfip.xemelios.data.ExportableData;
import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;

@SuppressWarnings("serial")
public class DlgExportAll extends DlgChooseDocuments {
    private static Logger logger = Logger.getLogger(DlgExportAll.class);
    private Action escapeAction;
    private XemeliosUser user;
    
    public DlgExportAll(java.awt.Frame parent, boolean modal, DocumentsModel _dm,XemeliosUser user) {
        super(parent, modal, _dm, false,user);
        this.user=user;
        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() {
        ExportableData datas =  ((PanelChooseDatabaseFichier)getJTabbedPane1().getSelectedComponent()).getData().getData();
        for (ExportableData d:datas.getChilds()) {
            exportData(d);
        }
    }
    
    protected void exportData(ExportableData datas) {
        // Si l'on veux exorter ce niveau
        if (datas.isSelected()) {
            doExportData(datas);
        } else {
            for (ExportableData d:datas.getChilds()) {
                exportData(d);
            }
        }
    }
    
    public void doExportData(ExportableData d) {
        DocumentModel dm = null;
        Pair collectivite = null;
        Pair budget = null;
        String fichier = null;
        
        // export selon le niveau
        switch (d.getLevel()) {
            case ExportableData.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 ExportableData.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()==ExportableData.LVL_BUD || d.getLevel()==ExportableData.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.QN);
                try { dmsTmp.addChild(dm, DocumentModel.QN); } catch (Throwable t) {}
                
                DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU,user);
                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 ExportableData.LVL_BUD: {
                budget = (Pair)dn.getData();
                collectivite = (Pair)dn.getParent().getData();
                dm = (DocumentModel)(dn.getParent().getParent().getData());
                break;
            }
            case ExportableData.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 ExportableData.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==ExportableData.LVL_BUD || level==ExportableData.TYPE_PERSO1 || level==ExportableData.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.QN);
                try { dmsTmp.addChild(dm, DocumentModel.QN); } catch (Throwable t) {}
                
                DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU,user);
                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;
    }
}
