/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fp.firma.applet;

import com.fp.firma.common.CertificateUtils;
import com.fp.firma.common.FirmMessages;
import com.itextpdf.text.Rectangle;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

/**
 * Applet de firma electr&oacute;nica a trav&eacute;s de token
 * @author dcruz
 */
public class FirmaApplet extends javax.swing.JApplet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String PREFIX = "firmado_";
    private String rutaArchivoFirmar = "";
    private static final Logger logger = Logger.getLogger(FirmaApplet.class .getName());
    
    private String tipoFirma;
    /**
     * Initializes the applet FirmaApplet
     */
    @Override
    public void init() {
//        FileHandler handler;
//        try {
//            handler = new FileHandler(System.getProperty("java.io.tmpdir")+"\\applet.txt");
//            handler.setFormatter(new SimpleFormatter());
//            logger.addHandler(handler);
//        } catch (IOException ex) {
//            Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (SecurityException ex) {
//            Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
//        }
        
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the init() method 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() {

        grupoRadios = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        labelArchivoFirma = new javax.swing.JLabel();
        txtRutaArchivo = new javax.swing.JTextField();
        btnExaminar = new javax.swing.JButton();
        btnFirmarArchivo = new javax.swing.JButton();
        tokenIkey = new javax.swing.JRadioButton();
        tokenAlladin = new javax.swing.JRadioButton();
        tokenSD = new javax.swing.JRadioButton();
        grupoRadios.add(tokenIkey);
        grupoRadios.add(tokenAlladin);
        grupoRadios.add(tokenSD);

        labelArchivoFirma.setText("Archivo a firmar");

        txtRutaArchivo.setEditable(false);
        btnFirmarArchivo.setEnabled(true);
        btnExaminar.setEnabled(true);

        btnExaminar.setText("Examinar");
        btnExaminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExaminarActionPerformed(evt);
            }
        });

        btnFirmarArchivo.setText("Firmar");
        btnFirmarArchivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFirmarArchivoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(labelArchivoFirma)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(btnFirmarArchivo))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExaminar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelArchivoFirma)
                    .addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExaminar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnFirmarArchivo)
                .addContainerGap())
        );

        tokenIkey.setText("iKey 2032");
        tokenIkey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tokenIkeyActionPerformed(evt);
            }
        });

        tokenAlladin.setText("eTokenPro");
        tokenAlladin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tokenAlladinActionPerformed(evt);
            }
        });

        tokenSD.setText("Security Data");
        tokenSD.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tokenSDActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(tokenIkey)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tokenAlladin)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tokenSD)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(75, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tokenAlladin)
                    .addComponent(tokenSD)
                    .addComponent(tokenIkey))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
        // TODO add your handling code here:
        try
        {
         /**llamamos el metodo que permite cargar la ventana*/
         JFileChooser fileChooser=new JFileChooser();
         String rutaArchivo = txtRutaArchivo.getText();
         File directorio = new File(rutaArchivo).getParentFile();         
         fileChooser.setCurrentDirectory(directorio);         
//         System.out.println("Directorio del archivo "+fileChooser.getCurrentDirectory() != null ? fileChooser.getCurrentDirectory().getAbsolutePath() : "");
         /**abrimos el archivo seleccionado*/
         int respuestaDialog = fileChooser.showOpenDialog(this);
         
         if(respuestaDialog == JFileChooser.APPROVE_OPTION){
             File fileSelected = fileChooser.getSelectedFile();
             rutaArchivoFirmar = fileSelected.getAbsolutePath();   
             System.out.println("Ruta del archivo escogido "+rutaArchivoFirmar);
             txtRutaArchivo.setText(rutaArchivoFirmar);
         } else{
             JOptionPane.showMessageDialog(null,"" +
                 "\nAccion cancelada por el usuario",
                       "ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
         }
         
         
         /**recorremos el archivo, lo leemos para plasmarlo
         *en el area de texto*/

        }catch(Throwable ex)
        {
           JOptionPane.showMessageDialog(null,ex+"" +
                 "\nNo se ha encontrado el archivo",
                       "ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnExaminarActionPerformed

    private void btnFirmarArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirmarArchivoActionPerformed
        // TODO add your handling code here:
        InputStream inputStream = null;
        try{
        	 String razon = getParameter("razon") != null ? getParameter("razon") : "";
             String lugar = getParameter("lugar") != null ? getParameter("lugar") : "";
             String nombreFirma = getParameter("firma") != null ? getParameter("firma") : "";
             Float llx = Float.valueOf(getParameter("llx") != null ? Float.parseFloat(getParameter("llx")) : 0.0F);
             Float lly = Float.valueOf(getParameter("lly") != null ? Float.parseFloat(getParameter("lly")) : 0.0F);
             Float urx = Float.valueOf(getParameter("urx") != null ? Float.parseFloat(getParameter("urx")) : 0.0F);
             Float ury = Float.valueOf(getParameter("ury") != null ? Float.parseFloat(getParameter("ury")) : 0.0F);
            if(tipoFirma == null){
                JOptionPane.showMessageDialog(null, "Debe seleccionar un Token con el cual firmar", "Tipo Firma", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if(txtRutaArchivo.getText() != null){
                JPasswordField txtPasswordToken = new JPasswordField();
                final JComponent[] components = new JComponent[]{new JLabel("Password:"), txtPasswordToken};
                JOptionPane.showMessageDialog(null, components, "TOKEN", JOptionPane.PLAIN_MESSAGE);
                if(txtPasswordToken.getPassword() == null){
                	throw new NullPointerException(FirmMessages.getString("FIR-0007"));
                }
                inputStream = new FileInputStream(txtRutaArchivo.getText());
                byte[] datos = CertificateUtils.sign(inputStream, null, new String(txtPasswordToken.getPassword()), razon, lugar, Boolean.FALSE.booleanValue(), Boolean.FALSE.booleanValue(), new Rectangle(llx.floatValue(), lly.floatValue(), urx.floatValue(), ury.floatValue()), 1, nombreFirma, this.tipoFirma);
                if(datos != null){
	                escribirArchivo(datos);
	                txtPasswordToken.setText("");
	                JOptionPane.showMessageDialog(null, "El archivo se modificado correctamente", "Archivo firmado", JOptionPane.INFORMATION_MESSAGE);
                }
            }else{
                JOptionPane.showMessageDialog(null, "Debe seleccionar un archivo", "Archivo no encontrado", JOptionPane.ERROR_MESSAGE);
            }
            btnFirmarArchivo.setEnabled(false);
            btnExaminar.setEnabled(false);
        } catch(IOException e){
            JOptionPane.showMessageDialog(null, e.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } finally{
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_btnFirmarArchivoActionPerformed

    public void escribirArchivo(byte[] data){
    	System.out.println("Ingreso a escribir el archivo");
        FileOutputStream fo = null;
        try {
            File archivoFirmado = new File(txtRutaArchivo.getText());
            fo = new FileOutputStream(archivoFirmado);
            fo.write(data);            
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error archivo no encontrado", JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error al escribir el archivo firmado", JOptionPane.ERROR_MESSAGE);
        } finally {
            try {
                fo.close();
            } catch (IOException ex) {
                Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private void tokenIkeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenIkeyActionPerformed
        // TODO add your handling code here:
        tipoFirma = "1";
    }//GEN-LAST:event_tokenIkeyActionPerformed

    private void tokenAlladinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenAlladinActionPerformed
        // TODO add your handling code here:
        tipoFirma = "2";
    }//GEN-LAST:event_tokenAlladinActionPerformed

    private void tokenSDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenSDActionPerformed
        // TODO add your handling code here:
        tipoFirma = "3";
    }//GEN-LAST:event_tokenSDActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExaminar;
    private javax.swing.JButton btnFirmarArchivo;
    private javax.swing.ButtonGroup grupoRadios;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelArchivoFirma;
    private javax.swing.JRadioButton tokenAlladin;
    private javax.swing.JRadioButton tokenIkey;
    private javax.swing.JRadioButton tokenSD;
    private javax.swing.JTextField txtRutaArchivo;
    // End of variables declaration//GEN-END:variables
}
