/*
 * Copyright 
 *   2008 axYus - www.axyus.com
 *   2008 jp.tessier - jean-philippe.tessier@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.plugin.generatorEdmn;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import fr.gouv.finances.cp.utils.ui.InfiniteGlassPane;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author  jp.tessier
 */
public class DlgGenEdmn extends javax.swing.JDialog {
	private static final long serialVersionUID = 3977304325945658517L;
//	private static String PATH_FILE_CHOOSER = "C:/XEMELIOS_FICHIERS/EDMN_2006/1trim";
	String lastDiredtory =""; 
    /** Creates new form DlgGenEdmn */
    public DlgGenEdmn(java.awt.Frame parent, boolean modal) {
        super(parent, "Générateur de flux EDMN", modal);
        initComponents();
        setLocationRelativeTo(getParent());
        InfiniteGlassPane glassPane = new InfiniteGlassPane();
        this.setGlassPane(glassPane);
        if(System.getProperty("xemelios.mysql.config.filename")==null){
        	browse_edmn.setVisible(false);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        file_edmn = new javax.swing.JTextField();
        browse_edmn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        file_index = new javax.swing.JTextField();
        browse_index = new javax.swing.JButton();
        cancel_button = new javax.swing.JButton();
        valid_button = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        dfBudgets = new javax.swing.JTextField();
        pbChooseBudgets = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        dfOrdos = new javax.swing.JTextField();
        pbChooseOrdos = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        dfComptables = new javax.swing.JTextField();
        pbChooseComptables = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        dfOutput = new javax.swing.JTextField();
        pbChooseOutput = new javax.swing.JButton();
        dfAnneeGestion = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Fichier EDMN");

        browse_edmn.setText("...");
        browse_edmn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browse_edmnActionPerformed(evt);
            }
        });

        jLabel2.setText("Fichier Index");

        browse_index.setText("...");
        browse_index.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browse_indexActionPerformed(evt);
            }
        });

        cancel_button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/deleteRow.png"))); // NOI18N
        cancel_button.setText("Fermer");
        cancel_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancel_buttonActionPerformed(evt);
            }
        });

        valid_button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/plugin/generatorEdmn/busy-icon0.png"))); // NOI18N
        valid_button.setText("Générer");
        valid_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                valid_buttonActionPerformed(evt);
            }
        });

        jLabel3.setText("Fichier Budgets");

        pbChooseBudgets.setText("...");
        pbChooseBudgets.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbChooseBudgetsActionPerformed(evt);
            }
        });

        jLabel4.setText("Fichier Ordonnateurs");

        pbChooseOrdos.setText("...");
        pbChooseOrdos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbChooseOrdosActionPerformed(evt);
            }
        });

        jLabel5.setText("Fichier Comptables");

        pbChooseComptables.setText("...");
        pbChooseComptables.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbChooseComptablesActionPerformed(evt);
            }
        });

        jLabel6.setText("Fichier de sortie");

        pbChooseOutput.setText("...");
        pbChooseOutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbChooseOutputActionPerformed(evt);
            }
        });

        jLabel7.setText("Année de Gestion");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1))
                            .add(jLabel3)
                            .add(jLabel4)
                            .add(jLabel5)
                            .add(jLabel6)
                            .add(jLabel7))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(dfOutput, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pbChooseOutput))
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(dfComptables, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                                    .add(dfOrdos, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                                    .add(dfBudgets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, file_index, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                                    .add(file_edmn, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(org.jdesktop.layout.GroupLayout.TRAILING, browse_edmn)
                                        .add(org.jdesktop.layout.GroupLayout.TRAILING, browse_index))
                                    .add(pbChooseBudgets)
                                    .add(pbChooseOrdos)
                                    .add(pbChooseComptables)))
                            .add(dfAnneeGestion, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 49, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(cancel_button)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(valid_button)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(browse_edmn)
                    .add(file_edmn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(browse_index)
                    .add(jLabel2)
                    .add(file_index, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(dfBudgets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(pbChooseBudgets))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(dfOrdos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(pbChooseOrdos))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(dfComptables, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(pbChooseComptables))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(pbChooseOutput)
                    .add(dfOutput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(dfAnneeGestion, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel7))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE, false)
                    .add(valid_button)
                    .add(cancel_button))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pbChooseBudgetsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbChooseBudgetsActionPerformed
        chooseFile(evt, dfBudgets);
    }//GEN-LAST:event_pbChooseBudgetsActionPerformed

    private void pbChooseOrdosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbChooseOrdosActionPerformed
        chooseFile(evt, dfOrdos);
    }//GEN-LAST:event_pbChooseOrdosActionPerformed

    private void pbChooseComptablesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbChooseComptablesActionPerformed
        chooseFile(evt, dfComptables);
    }//GEN-LAST:event_pbChooseComptablesActionPerformed

    private void pbChooseOutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbChooseOutputActionPerformed
        JFileChooser fc;
    	if(lastDiredtory.length()>0) {
    		fc = new JFileChooser(lastDiredtory);
    	} else if(System.getProperty("xemelios.edmn.directory")!=null) {
    		fc = new JFileChooser(System.getProperty("edmn.directory"));
    	} else {
    		fc = new JFileChooser();
    	}
    	fc.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toUpperCase().endsWith("XAR");
            }
            public String getDescription() {
                return "Archives Xemelios (.xar)";
            }
        });
        int reponse = fc.showSaveDialog(this);
        if(reponse==JFileChooser.APPROVE_OPTION) {
            dfOutput.setText(fc.getSelectedFile().getAbsolutePath());
            lastDiredtory=fc.getSelectedFile().getParent();
        }

    }//GEN-LAST:event_pbChooseOutputActionPerformed

    
    private void browse_edmnActionPerformed(java.awt.event.ActionEvent evt) {
        chooseFile(evt, file_edmn);
    }

    private void chooseFile(java.awt.event.ActionEvent evt, javax.swing.JTextField target) {
    	JFileChooser fc;
    	if(lastDiredtory.length()>0) {
    		fc = new JFileChooser(lastDiredtory);
    	} else if(System.getProperty("xemelios.edmn.directory")!=null) {
    		fc = new JFileChooser(System.getProperty("edmn.directory"));
    	} else {
    		fc = new JFileChooser();
    	}
    	fc.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toUpperCase().endsWith("TXT");
            }
            public String getDescription() {
                return "Fichiers texte (.txt)";
            }
        });
    	fc.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toUpperCase().endsWith("DAT");
            }
            public String getDescription() {
                return "Fichiers dat (.dat)";
            }
        });
//    	fc.addChoosableFileFilter(new FileFilter() {
//            public boolean accept(File f) {
//                return true;
//            }
//            public String getDescription() {
//                return "Fichiers INDEX";
//            }
//        });
        int reponse = fc.showOpenDialog(this);
        if(reponse==JFileChooser.APPROVE_OPTION) {
            target.setText(fc.getSelectedFile().getAbsolutePath());
            lastDiredtory=fc.getSelectedFile().getParent();
        }
    }

    private void browse_indexActionPerformed(java.awt.event.ActionEvent evt) {                                             
        chooseFile(evt,file_index);
    }

    private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        setVisible(false);
    }

    private void valid_buttonActionPerformed(java.awt.event.ActionEvent evt) {
        if(!checkSaisie()) return;
        EdmnImporter edmni = new EdmnImporter(this);
        try {
        	startVentilateur();
                edmni.importFile(
                    new File(file_edmn.getText()),
                    new File(file_index.getText()),
                    new File(dfBudgets.getText()),
                    new File(dfOrdos.getText()),
                    new File(dfComptables.getText()),
                    new File(dfOutput.getText()),
                    dfAnneeGestion.getText()
                    );
			stopVentilateur();
		} catch (Exception e) {
			stopVentilateur();
			e.printStackTrace();
		}
    }
    private boolean checkSaisie() {
        ComponentError err = null;
        if(err==null) err = checkFile(file_edmn,"EDMN");
        if(err==null) err = checkFile(file_index, "INDEX");
        if(err==null) err = checkFile(dfBudgets, "des budgets");
        if(err==null) err = checkFile(dfOrdos, "des ordonnateurs");
        if(err==null) err = checkFile(dfComptables,"des comptables");
        if(err==null && (dfOutput.getText()==null || dfOutput.getText().length()==0)) err = new ComponentError(dfOutput,"Le fihchier de sortie est obligatoire");
        if(err==null) {
            if(dfAnneeGestion.getText()==null || dfAnneeGestion.getText().length()<4) err = new ComponentError(dfAnneeGestion, "L'année de gestion est obligatoire");
        }
        if(err==null) {
            try {
                Integer.parseInt(dfAnneeGestion.getText());
            } catch(NumberFormatException nfEx) {
                err = new ComponentError(dfAnneeGestion,dfAnneeGestion.getText()+" n'est pas une année valide");
            }
        }
        if(err!=null) {
            JOptionPane.showMessageDialog(this, err.msg, "Erreur de saisie", JOptionPane.ERROR_MESSAGE);
            err.comp.requestFocus();
            return false;
        }
        return true;
    }
    private ComponentError checkFile(JTextField fld,String name) {
        if(fld.getText()==null || fld.getText().length()==0) {
            return new ComponentError(fld,"Le fichier "+name+" ne peut pas être vide");
        }
        if(!(new File(fld.getText()).exists())) {
            return new ComponentError(fld,"Le fichier EDMN n'existe pas");
        }
        return null;
    }
    private class ComponentError {
        JComponent comp;
        String msg;
        public ComponentError(JComponent comp,String msg) {
            super();
            this.comp=comp;
            this.msg = msg;
        }
    }
    public void enableGenerateButton() {
        valid_button.setEnabled(true);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DlgGenEdmn dialog = new DlgGenEdmn(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    public void stopVentilateur() {
        getGlassPane().setVisible(false);
    }
    
    public void startVentilateur() {
        getGlassPane().setVisible(true);
    }
        
    public void run() {
        setVisible(true);
    }
    
	public void setFile_edmn(String text) {
		this.file_edmn.setText(text);
	}

	public void setFile_index(String text) {
		this.file_index.setText(text);
	}
	
	public void setBrowseIndexEnabled(boolean b){
		browse_index.setEnabled(b);
	}
	
	public void setValidBouttonEnabled(boolean b){
		valid_button.setEnabled(b);
	}
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browse_edmn;
    private javax.swing.JButton browse_index;
    private javax.swing.JButton cancel_button;
    private javax.swing.JTextField dfAnneeGestion;
    private javax.swing.JTextField dfBudgets;
    private javax.swing.JTextField dfComptables;
    private javax.swing.JTextField dfOrdos;
    private javax.swing.JTextField dfOutput;
    private javax.swing.JTextField file_edmn;
    private javax.swing.JTextField file_index;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JButton pbChooseBudgets;
    private javax.swing.JButton pbChooseComptables;
    private javax.swing.JButton pbChooseOrdos;
    private javax.swing.JButton pbChooseOutput;
    private javax.swing.JButton valid_button;
    // End of variables declaration//GEN-END:variables

    
    
}
