/* 
* Copyright 2016 Agencia Estatal de Administración Tibutaria
*
* Licencia con arreglo a la EUPL, Versión 1.1 o –en cuanto
* sean aprobadas por la Comisión Europea– versiones
* posteriores de la EUPL (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en:
*  
* https://joinup.ec.europa.eu/software/page/eupl
*  
* Salvo cuando lo exija la legislación aplicable o se acuerde
* por escrito, el programa distribuido con arreglo a la
* Licencia se distribuye «TAL CUAL», SIN GARANTÍAS NI CONDICIONES
* DE NINGÚN TIPO, ni expresasni implícitas.
*
* Véase la Licencia en el idioma concreto que rige los permisos y 
* limitaciones que establece la Licencia.
*/ 


package administrador;

/**
 *
 * @author DPI
 */
import java.awt.Cursor;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public final class FormPresentes extends javax.swing.JFrame {

    /**
     * Creates new form FormPresentes
     */
    javax.swing.table.DefaultTableModel modelo;

    public FormPresentes(String msj) {
        initComponents();
        formateaTabla(msj);
        ajustarTamaño();
        this.setLocationRelativeTo(null);

    }

    void ajustarTamaño() {
        TableColumn column = null;
        for (int i = 0; i < jTable1.getColumnCount(); i++) {
            column = jTable1.getColumnModel().getColumn(i);
            if (i < 3) {
                column.setPreferredWidth(50); 
            }
            if (i == 3) {
                column.setPreferredWidth(80); 
            }
            if (i == 4) {
                column.setPreferredWidth(120);
            }
            if (i > 4) {
                column.setPreferredWidth(150);
            }
        }
    }

    void formateaTabla(String msj) {
        if (msj.length() < 10) {
            this.jLabel1.setText("No hay datos");
            return;
        }
        this.jExportar.setEnabled(true);
        modelo = (DefaultTableModel) jTable1.getModel();

        String[] lineas = msj.split("!#");
        if (lineas.length > 29) {
            this.jLabel1.setText("Solo se muestran los 30 primeros registros.");
        }
        for (String linea : lineas) {
            String[] datos = split(linea, '|');
            modelo.addRow(datos);
        }
        jTable1.setModel(modelo);
    }

    public synchronized static String[] split(String s, char sep) {
        java.util.ArrayList<String> array = new java.util.ArrayList<>();
        int comi = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == sep) {
                array.add(s.substring(comi, i));
                comi = i + 1;
            }
        }
        if (comi < s.length()) {
            array.add(s.substring(comi));
        }

        String[] res = new String[array.size()];
        return array.toArray(res);
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jExportar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Presentes Por Hora Cita");
        setMinimumSize(new java.awt.Dimension(578, 498));

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Orden", "Cola", "Numero", "Iden.Fis", "Nombre", "HoraCalculada", "HoraPresente"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setOpaque(false);
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Presentes ordenados por Hora Cita Hora Presente.");

        jExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/EXCEL.gif"))); // NOI18N
        jExportar.setText("Exportar");
        jExportar.setEnabled(false);
        jExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jExportarActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                        .addComponent(jExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(66, 66, 66))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jExportar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
                .addGap(31, 31, 31))
        );

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

    private void jExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jExportarActionPerformed
        ExportaAHojaExcell();
}//GEN-LAST:event_jExportarActionPerformed
    public void ExportaAHojaExcell() {
        try {
            this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

            String ficheroExcel = crearFicheroXLS(modelo);
            Runtime.getRuntime().exec("rundll32 shell32.dll,ShellExec_RunDLL \"" + ficheroExcel + "\"");
            setCursor(Cursor.getDefaultCursor());

        } catch (IOException ex) {
            setCursor(Cursor.getDefaultCursor());

            ex.printStackTrace();
        }
    }

    public String crearFicheroXLS(DefaultTableModel modelo) {
        try {
            File temp = File.createTempFile("Presentes", ".xls");
            int cab = modelo.getColumnCount();
            int row = modelo.getRowCount();

            PrintWriter out = new PrintWriter(new FileWriter(temp));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cab; i++) {
                sb.append(modelo.getColumnName(i)).append("\t");
            }
            out.println(sb.toString());
            for (int i = 0; i < row; i++) {
                sb = new StringBuilder();
                for (int col = 0; col < (cab); col++) {
                    sb.append(modelo.getValueAt(i, col)).append("\t");
                }
                out.println(sb.toString());
            }
            out.close();
            return temp.getAbsolutePath();
        } catch (IOException e) {
            return "error";
        }
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new FormPresentes().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jExportar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

}
