/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert.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.plugin.signerfichier;

import fr.gouv.finances.dgfip.xemelios.common.Constants;
import java.io.File;
import java.awt.Component;
import java.io.FileFilter;
import java.util.ArrayList;
import org.netbeans.spi.wizard.WizardPage;

/**
 *
 * @author  laurent.meckert
 */
public class InputFilePanel extends WizardPage {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(InputFilePanel.class);
    private static final long serialVersionUID = 7621780388749506917L;

    /** Creates new form InputFilePanel */
    public InputFilePanel() {
        initComponents();
    }

    void showSelectedInputFile(File f) {
        textFieldInputFile.setText(f.getAbsolutePath());
        if(SignerFichierPlugin.isInXemelios()) {
            pbViewFile.setEnabled(true);
        }
    }

    @Override
    protected String validateContents(Component comp, Object o) {
        if (textFieldInputFile.getText().length() == 0) {
            return "Sélectionner un fichier SVP";
        } else {
            return null;
        }
    }

    public static final String getDescription() {
        return "Sélection du fichier à signer";
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        textFieldInputFile = new javax.swing.JTextField();
        jButtonInputFile = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        pbViewFile = new javax.swing.JButton();

        textFieldInputFile.setEditable(false);
        textFieldInputFile.setName("TextFieldInputFile"); // NOI18N

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

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 10));
        jLabel3.setText("Utiliser le bouton de navigation ... pour sélectionner le fichier à signer");

        jLabel4.setText("Fichier à signer");

        pbViewFile.setText("Visualiser le fichier...");
        pbViewFile.setEnabled(false);
        pbViewFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbViewFileActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(textFieldInputFile, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 513, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonInputFile)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(212, 212, 212))
                    .add(layout.createSequentialGroup()
                        .add(jLabel4)
                        .addContainerGap(479, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(pbViewFile)
                        .addContainerGap(412, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonInputFile)
                    .add(textFieldInputFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pbViewFile)
                .addContainerGap(209, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jButtonInputFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInputFileActionPerformed

    try {
        Actions.getInstance().chooseInputFile();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (Actions.getInstance().getFileToSign() != null) {
        showSelectedInputFile(Actions.getInstance().getFileToSign());
        setProblem(null);
    }

}//GEN-LAST:event_jButtonInputFileActionPerformed

private void pbViewFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbViewFileActionPerformed
    Runnable r = new Runnable() {
        public void run() {
            try {
//                setBusy(false);
                //ViewXemeliosDocument.main(new String[] {textFieldInputFile.getText(),"PES_Aller"});
//                String cmd = System.getProperty("xemelios.prg")+"/root/viewdoc.cmd";
//                File f = new File(cmd);
//                cmd = f.getAbsolutePath();
//                if(cmd.split(" ").length>1) cmd = "\""+cmd+"\"";
//                String fileName = null;
//                if(textFieldInputFile.getText().split(" ").length>1)
//                    fileName = "\""+textFieldInputFile.getText()+"\"";
//                else
//                    fileName = textFieldInputFile.getText();
//                String fullCmd = cmd+" "+fileName+" PES_Aller";
//                //Runtime.getRuntime().exec(fullCmd);
//                ProcessBuilder pb = new ProcessBuilder("viewdoc.cmd",fileName,"PES_Aller");
//                pb.directory(new File(System.getProperty("xemelios.prg")+"/root"));
//                pb.start();
// Nouvelle methode
                String cpSeparator = System.getProperty("path.separator");
                File libDir = new File(System.getProperty("xemelios.lib"));
                StringBuffer cp = new StringBuffer();
                if(libDir.exists()) {
                    File[] jars = libDir.listFiles(new FileFilter() {
                        public boolean accept(File pathname) {
                            return pathname.getName().endsWith(".jar");
                        }
                    });
                    for(File jar:jars) {
                        cp.append(jar.getAbsolutePath()).append(cpSeparator);
                    }
                }
                if(cp.length()>0) cp.deleteCharAt(cp.length()-1);
                ArrayList<String> cmds = new ArrayList<String>();
                boolean windows = System.getProperty("os.name").toUpperCase().indexOf("WINDOWS")>=0;
                String fileName = textFieldInputFile.getText();
                cmds.add(windows?"javaw":"java");
                cmds.add("-cp");
                cmds.add(cp.toString());
                cmds.add("-D"+Constants.SYS_PROP_DOC_DEF_DIR+"="+System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR)+"");
                cmds.add("fr.gouv.finances.cp.xemelios.ui.ViewXemeliosDocument");
                cmds.add(fileName);
                cmds.add("PES_Aller");
                ProcessBuilder pb2 = new ProcessBuilder(cmds);
                pb2.directory(new File(System.getProperty("xemelios.prg")+"/root"));
                pb2.start();
            } catch(Throwable t) {
                t.printStackTrace();
            }
        }
    };
    Thread th = new Thread(r);
    th.start();

}//GEN-LAST:event_pbViewFileActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonInputFile;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JButton pbViewFile;
    private javax.swing.JTextField textFieldInputFile;
    // End of variables declaration//GEN-END:variables
}
