/*
 * DlgMakePJ.java
 *
 * Created on 28 janvier 2008, 13:08
 */


package fr.gouv.finances.cp.xemelios.plugin.generatorPesPjs;

import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import org.jdesktop.swingx.action.AbstractActionExt;

/**
 *
 * @author  jp.tessier
 */
public class DlgMakePJ extends javax.swing.JDialog {
    private JFrame parentWindow;
    private TableModelRefCompta tableModel = new TableModelRefCompta();
    private PJ piece_justificative;
    private String idcol,idpost,codcol,codbud;
    private boolean bRet;
    private boolean isEdit=false;
    private Action escapeAction,enterAction;
    private Vector<String> vMIME_TYPE = new Vector<String>();
    
    /** Creates new form DlgMakePJ */
    public DlgMakePJ(JFrame parent, boolean modal) {
        super(parent, modal);
        parentWindow=parent;
        
        initComponents();
        initMIMETYPE();
	tableRefsComptas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setLocationRelativeTo(parent);
    }
    
    /** 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() {

        onglets = new javax.swing.JTabbedPane();
        PanelPj = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        type_pj = new javax.swing.JComboBox();
        pieceJustificative = new javax.swing.JTextField();
        id_unique = new javax.swing.JTextField();
        PjName = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        description = new javax.swing.JTextArea();
        browse_button = new javax.swing.JButton();
        PanelRefsComptas = new javax.swing.JPanel();
        add_refCompta_button = new javax.swing.JButton();
        edit_refcompta_button = new javax.swing.JButton();
        deleteRefCompta = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tableRefsComptas = new JTable(){
            public void valueChanged(ListSelectionEvent evt) {
                super.valueChanged(evt);
                showHideButtons(evt);
            }
        };
        cancel_button = new javax.swing.JButton();
        save_button = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Création de la PJ");

        onglets.setEnabled(false);

        jLabel1.setText("Pièces Justificative");

        jLabel2.setText("Identifiant Unique");

        jLabel3.setText("Nom PJ");

        jLabel4.setText("Type PJ");

        jLabel5.setText("Description");

        type_pj.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "001 - Document Budgétaire", "002 - Facture de Recette", "003 - Facture de Dépense", "004 - Etat de Paye", "005 - Etat d'Aide sociale" }));
        type_pj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                type_pjActionPerformed(evt);
            }
        });

        pieceJustificative.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                pieceJustificativeCaretUpdate(evt);
            }
        });

        PjName.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                PjNameFocusLost(evt);
            }
        });
        PjName.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                PjNameCaretUpdate(evt);
            }
        });

        description.setColumns(20);
        description.setRows(5);
        jScrollPane1.setViewportView(description);

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

        org.jdesktop.layout.GroupLayout PanelPjLayout = new org.jdesktop.layout.GroupLayout(PanelPj);
        PanelPj.setLayout(PanelPjLayout);
        PanelPjLayout.setHorizontalGroup(
            PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelPjLayout.createSequentialGroup()
                .addContainerGap()
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel4)
                    .add(jLabel3)
                    .add(jLabel2)
                    .add(jLabel1)
                    .add(jLabel5))
                .add(18, 18, 18)
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(PanelPjLayout.createSequentialGroup()
                        .add(pieceJustificative, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 292, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(browse_button))
                    .add(id_unique)
                    .add(PjName)
                    .add(type_pj, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jScrollPane1))
                .addContainerGap())
        );
        PanelPjLayout.setVerticalGroup(
            PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelPjLayout.createSequentialGroup()
                .addContainerGap()
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(browse_button)
                    .add(pieceJustificative, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(id_unique, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(PjName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(type_pj, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelPjLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        onglets.addTab("Pièce Justificative", PanelPj);

        add_refCompta_button.setText("Ajouter");
        add_refCompta_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                add_refCompta_buttonActionPerformed(evt);
            }
        });

        edit_refcompta_button.setText("Editer");
        edit_refcompta_button.setEnabled(false);
        edit_refcompta_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edit_refcompta_buttonActionPerformed(evt);
            }
        });

        deleteRefCompta.setText("Supprimer");
        deleteRefCompta.setEnabled(false);
        deleteRefCompta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteRefComptaActionPerformed(evt);
            }
        });

        tableRefsComptas.setModel(tableModel);
        tableRefsComptas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableRefsComptasMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tableRefsComptas);

        org.jdesktop.layout.GroupLayout PanelRefsComptasLayout = new org.jdesktop.layout.GroupLayout(PanelRefsComptas);
        PanelRefsComptas.setLayout(PanelRefsComptasLayout);
        PanelRefsComptasLayout.setHorizontalGroup(
            PanelRefsComptasLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelRefsComptasLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(PanelRefsComptasLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, deleteRefCompta, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, edit_refcompta_button, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                    .add(add_refCompta_button, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE))
                .addContainerGap())
        );
        PanelRefsComptasLayout.setVerticalGroup(
            PanelRefsComptasLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelRefsComptasLayout.createSequentialGroup()
                .add(PanelRefsComptasLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(PanelRefsComptasLayout.createSequentialGroup()
                        .add(64, 64, 64)
                        .add(add_refCompta_button)
                        .add(26, 26, 26)
                        .add(edit_refcompta_button)
                        .add(27, 27, 27)
                        .add(deleteRefCompta))
                    .add(PanelRefsComptasLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)))
                .addContainerGap())
        );

        onglets.addTab("Références Comptables", PanelRefsComptas);

        cancel_button.setText("Annuler");
        cancel_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancel_buttonActionPerformed(evt);
            }
        });

        save_button.setText("Enregistrer");
        save_button.setEnabled(false);
        save_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                save_buttonActionPerformed(evt);
            }
        });

        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.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(cancel_button)
                        .add(18, 18, 18)
                        .add(save_button))
                    .add(onglets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(onglets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(save_button)
                    .add(cancel_button))
                .addContainerGap())
        );

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

    private void type_pjActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_type_pjActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_type_pjActionPerformed

    private void PjNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PjNameFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_PjNameFocusLost

    private void browse_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browse_buttonActionPerformed
        JFileChooser fc = new JFileChooser();
      
        int reponse = fc.showOpenDialog(this);
        if(reponse==JFileChooser.APPROVE_OPTION) {
            pieceJustificative.setText(fc.getSelectedFile().getAbsolutePath());
            PjName.setText(fc.getSelectedFile().getName());
            boolean isGoodExtension = false;
            for(String ext:vMIME_TYPE){
                if(fc.getSelectedFile().getAbsolutePath().toUpperCase().endsWith(ext)){
                    isGoodExtension=true;
                }
            }
            if(!isGoodExtension){
                JOptionPane.showMessageDialog(this,"Attention, l'extension du fichier de la PJ n'est pas reconnue.","Avertissement",JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_browse_buttonActionPerformed

    private void add_refCompta_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_refCompta_buttonActionPerformed
        DlgEditRefCompta dlgRefCompta = new DlgEditRefCompta(parentWindow,true);
        if(dlgRefCompta.run()) {
            tableModel.add(dlgRefCompta.getReferenceComptable());
        }
    }//GEN-LAST:event_add_refCompta_buttonActionPerformed

    private void edit_refcompta_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_refcompta_buttonActionPerformed
        editRefCompta();
    }//GEN-LAST:event_edit_refcompta_buttonActionPerformed

    private void deleteRefComptaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteRefComptaActionPerformed
        tableModel.remove(tableRefsComptas.getSelectedRow());
    }//GEN-LAST:event_deleteRefComptaActionPerformed

    private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancel_buttonActionPerformed

    private void save_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save_buttonActionPerformed
       savePJ();
    }//GEN-LAST:event_save_buttonActionPerformed

    private void savePJ(){
        Vector<RefCompta> vrefcompta = new Vector<RefCompta>();
        for(int i=0;i<tableModel.getRowCount();i++){
            vrefcompta.add(tableModel.getData(i));
        }
        if(id_unique.getText().length() == 0){
            SimpleDateFormat d = new SimpleDateFormat("ddyyMMHHmm");
            //id_unique.setText(idcol+"_"+idpost+"_"+codcol+"_"+d.format(new Date()));
            id_unique.setText(idcol+idpost+codcol+d.format(new Date()));
        }
        
        if(!isEdit){
            piece_justificative = new PJ(new File(pieceJustificative.getText()),id_unique.getText(),PjName.getText(),type_pj.getSelectedItem().toString(),description.getText(),vrefcompta);
        }else{
            piece_justificative.modifPJ(new File(pieceJustificative.getText()),id_unique.getText(),PjName.getText(),type_pj.getSelectedItem().toString(),description.getText(),vrefcompta);
        }
        bRet = true;
        setVisible(false);
    }
    
    private void showHideButtons(ListSelectionEvent evt){
        if(evt.getFirstIndex() >= 0 && tableRefsComptas.getSelectedRow() != -1){
           edit_refcompta_button.setEnabled(true); 
           deleteRefCompta.setEnabled(true); 
        }else{
           edit_refcompta_button.setEnabled(false); 
           deleteRefCompta.setEnabled(false); 
        }
    }
    
    private void pieceJustificativeCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_pieceJustificativeCaretUpdate
        dochek();
    }//GEN-LAST:event_pieceJustificativeCaretUpdate

    private void PjNameCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_PjNameCaretUpdate
        dochek();
    }//GEN-LAST:event_PjNameCaretUpdate

    private void tableRefsComptasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableRefsComptasMouseClicked
        if(tableRefsComptas.getSelectedRow() != -1 && evt.getClickCount() == 2 && evt.getButton() == MouseEvent.BUTTON1){
            editRefCompta();
        }
    }//GEN-LAST:event_tableRefsComptasMouseClicked
        
    public boolean run() {
        initComportement();
        setVisible(true);
        return bRet;
    }
    
    public boolean runEdit(PJ pj) {
        isEdit=true;
        piece_justificative=pj;
        save_button.setEnabled(true);
        initDlg();
        setVisible(true);
        return bRet;
    }
    
    private void initComportement(){
        tableRefsComptas.setModel(tableModel);
    }
    
    private void initMIMETYPE(){
        vMIME_TYPE.add("XML");
        vMIME_TYPE.add("XHL");
        vMIME_TYPE.add("DOC");
        vMIME_TYPE.add("PNG");
        vMIME_TYPE.add("JPG");
        vMIME_TYPE.add("BMP");
        vMIME_TYPE.add("PDF");
        vMIME_TYPE.add("HTML");
        vMIME_TYPE.add("XLS");
    }
    
    private void editRefCompta(){
        DlgEditRefCompta dlgRefCompta = new DlgEditRefCompta(parentWindow,true);
        int rowSeleted = tableRefsComptas.getSelectedRow();
        if(dlgRefCompta.runEdit(tableModel.getData(rowSeleted))) {
            tableModel.refresh();
        }
    }
    
    private void initDlg(){
        pieceJustificative.setText(piece_justificative.getPjFile().getAbsolutePath());
        id_unique.setText(piece_justificative.getIdentifiant());
        PjName.setText(piece_justificative.getNamePJ());
        for(int i=0;i<type_pj.getItemCount();i++){
            if(type_pj.getItemAt(i).equals(piece_justificative.getTypePJ())){
                type_pj.setSelectedIndex(i);
            }
        }
        description.setText(piece_justificative.getDescription());
        for(RefCompta rc:piece_justificative.getVRefsComptas()){
            tableModel.add(rc);
        }
    }
    
    private void dochek(){
        if(pieceJustificative.getText().length() > 0 && PjName.getText().length() > 0){
           onglets.setEnabled(true);
           save_button.setEnabled(true);
        }else{
           onglets.setEnabled(false);
           save_button.setEnabled(false);
        }
    }
    
    public PJ getPiece_justificative(){
        return piece_justificative;
    }
    
    public void setIdCollIdPostCodBud(String idc,String idp,String codc,String codb){
        idcol=idc;
        idpost=idp;
        codcol=codc;
        codbud=codb;
    }
    
    @Override
    protected JRootPane createRootPane() {    
        KeyStroke ksEsc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        KeyStroke ksEnter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
        
	JRootPane rp = new JRootPane();
        escapeAction = new AbstractActionExt("Fermer") {
		    /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;

            public void actionPerformed(ActionEvent evt) {
		        setVisible(false);
		    }

            public void itemStateChanged(ItemEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        	};
        
        enterAction = new AbstractActionExt("Save") {
		    /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;

            public void actionPerformed(ActionEvent evt) {
		        savePJ();
		    }

            public void itemStateChanged(ItemEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        	};
	rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ksEsc,JComponent.WHEN_IN_FOCUSED_WINDOW);
        rp.registerKeyboardAction(enterAction,"TOTOTOTO",ksEnter,JComponent.WHEN_IN_FOCUSED_WINDOW);
	return rp;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelPj;
    private javax.swing.JPanel PanelRefsComptas;
    private javax.swing.JTextField PjName;
    private javax.swing.JButton add_refCompta_button;
    private javax.swing.JButton browse_button;
    private javax.swing.JButton cancel_button;
    private javax.swing.JButton deleteRefCompta;
    private javax.swing.JTextArea description;
    private javax.swing.JButton edit_refcompta_button;
    private javax.swing.JTextField id_unique;
    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.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane onglets;
    private javax.swing.JTextField pieceJustificative;
    private javax.swing.JButton save_button;
    private javax.swing.JTable tableRefsComptas;
    private javax.swing.JComboBox type_pj;
    // End of variables declaration//GEN-END:variables
    
}
