/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Calculos_automaticos;

//import static arql2020.ARQL2020.capa_nivel;
//import static arql2020.ARQL2020.cuadro;
//import static arql2020.ARQL2020.episodio_estruct_planta;
//import static arql2020.ARQL2020.estruct_arq;
//import static arql2020.ARQL2020.localidad;
//import static arql2020.ARQL2020.microsector;
//import static arql2020.ARQL2020.nombre_estruct_planta;
//import static arql2020.ARQL2020.piso_subcapa;
//import static arql2020.ARQL2020.siglasitio;
//import static arql2020.ARQL2020.sitio;
//import static arql2020.ARQL2020.tipo_estruct_planta;
//import static arql2020.ARQL2020.zona_ambiental;
//import arql2020.DT_sintalon;
//import static arql2020.Internal_DT_sintalon.btn_eliminarregistro_Dt_sintalon;
//import static arql2020.Internal_DT_sintalon.st4_peso;
import static arql2020.ARQL2020.etiqueta_muestra;
import static arql2020.ARQL2020.WHERE;
import static Calculos_automaticos.Calculos.txt_muestra_seleccionada;
import static arql2020.ARQL2020.ventanamuestra;
import static arql2020.DT_frame.txt_muestra_DT;
import static arql2020.FORMATIZADOS_frame.txt_cargar_solo;
import clases.conexion;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author chuen
 */
public class Muestras extends javax.swing.JFrame {

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

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

        jPopupMenu1 = new javax.swing.JPopupMenu();
        seleccionar = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        eliminar = new javax.swing.JMenuItem();
        expandir = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabla_muestras_guardadas = new javax.swing.JTable();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        btn_guardar = new javax.swing.JButton();
        jLabel15 = new javax.swing.JLabel();
        txt_etiqueta = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        txt_sentencia = new javax.swing.JTextArea();
        jScrollPane4 = new javax.swing.JScrollPane();
        txt_descripcion = new javax.swing.JTextArea();

        seleccionar.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        seleccionar.setText("Seleccionar");
        seleccionar.setToolTipText("");
        seleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seleccionarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(seleccionar);
        jPopupMenu1.add(jSeparator1);

        eliminar.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        eliminar.setForeground(new java.awt.Color(255, 51, 0));
        eliminar.setText("Eliminar");
        eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(eliminar);

        expandir.setText("Expandir");
        expandir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                expandirActionPerformed(evt);
            }
        });
        jPopupMenu1.add(expandir);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(51, 51, 51));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("MUESTRAS GUARDADAS");

        tabla_muestras_guardadas.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        tabla_muestras_guardadas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Etiqueta", "Descripcion", "Sentencia"
            }
        ));
        tabla_muestras_guardadas.setComponentPopupMenu(jPopupMenu1);
        tabla_muestras_guardadas.setRowHeight(20);
        jScrollPane2.setViewportView(tabla_muestras_guardadas);

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel12.setForeground(new java.awt.Color(255, 255, 255));
        jLabel12.setText("DESCRIPCION");

        jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel13.setForeground(new java.awt.Color(255, 255, 255));
        jLabel13.setText("SENTENCIA");

        btn_guardar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btn_guardar.setText("Guardar esta muestra");
        btn_guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_guardarActionPerformed(evt);
            }
        });

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel15.setForeground(new java.awt.Color(255, 255, 255));
        jLabel15.setText("ETIQUETA");

        txt_etiqueta.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        txt_sentencia.setEditable(false);
        txt_sentencia.setColumns(20);
        txt_sentencia.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
        txt_sentencia.setLineWrap(true);
        txt_sentencia.setRows(5);
        txt_sentencia.setWrapStyleWord(true);
        jScrollPane3.setViewportView(txt_sentencia);

        txt_descripcion.setColumns(20);
        txt_descripcion.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
        txt_descripcion.setLineWrap(true);
        txt_descripcion.setRows(5);
        txt_descripcion.setWrapStyleWord(true);
        txt_descripcion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_descripcionKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_descripcionKeyTyped(evt);
            }
        });
        jScrollPane4.setViewportView(txt_descripcion);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel15)
                                .addGap(18, 18, 18)
                                .addComponent(txt_etiqueta, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(btn_guardar)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel12)
                                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(41, 41, 41)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel13)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(jScrollPane2)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(296, 296, 296)
                        .addComponent(jLabel1)))
                .addContainerGap(711, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txt_etiqueta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel13)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addComponent(btn_guardar)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 767, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

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

    private void btn_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_guardarActionPerformed
String a = txt_etiqueta.getText();
String b = txt_descripcion.getText();
String c = txt_sentencia.getText();

if((a.contains(";"))||(b.contains(";"))||(c.contains(";"))){
    JOptionPane.showMessageDialog(null, "Alguno de los campos contiene el siguiente caracter ';'. \n Elimínelo e intente nuevamente");
}else{
    if(c.equals("")){
      JOptionPane.showMessageDialog(null, "Para ingresar una muestra nueva, diríjase al menú Muestras/Generar muestra");  
    }else{
        DefaultTableModel dtm = (DefaultTableModel) tabla_muestras_guardadas.getModel();

        Object[] fila = new Object[3];

        fila[0] = txt_etiqueta.getText();
        fila[1] = txt_descripcion.getText();
        fila[2] = txt_sentencia.getText();
        dtm.addRow(fila);

        guardaTabla(tabla_muestras_guardadas);
        
    }
           
}

        

    }//GEN-LAST:event_btn_guardarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
cargartabla();
    }//GEN-LAST:event_formWindowOpened

    private void seleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seleccionarActionPerformed
int filaselec = tabla_muestras_guardadas.getSelectedRow();
if(filaselec>-1){
    String muestra = (String) tabla_muestras_guardadas.getValueAt(filaselec,0);
    if(ventanamuestra.equals("ANALISIS")){
    txt_muestra_seleccionada.setText(muestra);        
    }else if(ventanamuestra.equals("UTILES")){
    txt_cargar_solo.setText(muestra);    
    }
    else if(ventanamuestra.equals("DT")){
    txt_muestra_DT.setText(muestra);    
    }
  
    this.dispose();
    etiqueta_muestra=muestra;
    WHERE=(String) tabla_muestras_guardadas.getValueAt(filaselec,2);
}
    }//GEN-LAST:event_seleccionarActionPerformed

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

int result = JOptionPane.showConfirmDialog(null,"¿Está seguro que desea eliminar la muestra seleccionada?", "Swing Tester",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE);
            if(result == JOptionPane.YES_OPTION){
                int filaselec = tabla_muestras_guardadas.getSelectedRow();
                if(filaselec>-1){
                    DefaultTableModel dtm = (DefaultTableModel) tabla_muestras_guardadas.getModel();
                    dtm.removeRow(filaselec);
                    guardaTabla(tabla_muestras_guardadas);
                }
            }else if (result == JOptionPane.NO_OPTION){
                
            }else {
                
            }        
        
        

    }//GEN-LAST:event_eliminarActionPerformed

    private void txt_descripcionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_descripcionKeyTyped

    }//GEN-LAST:event_txt_descripcionKeyTyped

    private void txt_descripcionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_descripcionKeyPressed
if (evt.getKeyChar() != evt.VK_ENTER && evt.getKeyChar() != evt.VK_TAB  )
				{
				} else {
   
    evt.consume();
    }


    }//GEN-LAST:event_txt_descripcionKeyPressed

    private void expandirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expandirActionPerformed
btn_guardar.setEnabled(false);
int filaselec = tabla_muestras_guardadas.getSelectedRow();

if(filaselec>-1){
    btn_guardar.setEnabled(false);
    txt_etiqueta.setText(tabla_muestras_guardadas.getValueAt(filaselec, 0).toString());
    txt_descripcion.setText(tabla_muestras_guardadas.getValueAt(filaselec, 1).toString());
    txt_sentencia.setText(tabla_muestras_guardadas.getValueAt(filaselec, 2).toString());
}

    }//GEN-LAST:event_expandirActionPerformed
private void guardaTabla(JTable table){
        try {
            File f = new File("src/DatosMuestras.txt");
            if(!f.exists()){
                 f.createNewFile();
            }
                
            String sucursalesCSVFile = "src/DatosMuestras.txt";
            BufferedWriter bfw = new BufferedWriter(new FileWriter(sucursalesCSVFile ));

            for (int i = 0 ; i < table.getRowCount(); i++) //realiza un barrido por filas.
            {
                for(int j = 0 ; j < table.getColumnCount();j++) //realiza un barrido por columnas.
                {
                    bfw.write((String)(table.getValueAt(i,j)));
                    if (j < table.getColumnCount() -1) { //agrega separador "," si no es el ultimo elemento de la fila.
                        bfw.write(";");
                    }
                }
                bfw.newLine(); //inserta nueva linea.
            }

            bfw.close(); //cierra archivo!
            JOptionPane.showMessageDialog(null, "Se guardaron los cambios");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "No se pudieron guardar los cambios: "+e);        }
    }

public void cargartabla(){
  DefaultTableModel dtm = (DefaultTableModel) tabla_muestras_guardadas.getModel();  
            try {

            BufferedReader br = new BufferedReader(new FileReader(new File("src/DatosMuestras.txt")));
            List<String[]> elements = new ArrayList<String[]>();
            String line = null;
            while((line = br.readLine())!=null) {
                String[] splitted = line.split(";");
                elements.add(splitted);
            }
            br.close();

            
            Object[] content = new Object[3];

            for(int i=0; i<elements.size(); i++) {
                content[0] = elements.get(i)[0];
                content[1] = elements.get(i)[1];
                content[2] = elements.get(i)[2];
                dtm.addRow(content);
            }
           
            

            

        } catch (Exception ex) {
            ex.printStackTrace();
        }
}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* 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(Muestras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Muestras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Muestras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Muestras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Muestras().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton btn_guardar;
    private javax.swing.JMenuItem eliminar;
    private javax.swing.JMenuItem expandir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JMenuItem seleccionar;
    private javax.swing.JTable tabla_muestras_guardadas;
    private javax.swing.JTextArea txt_descripcion;
    private javax.swing.JTextField txt_etiqueta;
    public static javax.swing.JTextArea txt_sentencia;
    // End of variables declaration//GEN-END:variables
}
