/*
 * 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 arql2020;

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 static arql2020.Internal_DT_sintalon.btn_eliminarregistro_Dt_sintalon;
import static arql2020.Internal_DT_sintalon.st4_peso;
import clases.Cargar_MP;
import clases.InteraccionesBD;
import clases.conexion;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author chuen
 */
public class MateriasPrimas extends javax.swing.JFrame {

    /**
     * Creates new form MateriasPrimas
     */
    public MateriasPrimas() {
        initComponents();
        this.setExtendedState(MAXIMIZED_BOTH);
    }

    /**
     * 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();
        eliminar = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txt_abrev = new javax.swing.JTextField();
        txt_nombreext = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();

        eliminar.setText("Eliminar la materia prima seleccionada");
        eliminar.setToolTipText("");
        eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(eliminar);

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

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

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

            },
            new String [] {
                "Materia prima", "Referencia"
            }
        ));
        jTable1.setComponentPopupMenu(jPopupMenu1);
        jTable1.setRowHeight(30);
        jScrollPane2.setViewportView(jTable1);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Materias primas guardadas");

        txt_abrev.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_abrev.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_abrevKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_abrevKeyTyped(evt);
            }
        });

        txt_nombreext.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_nombreext.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_nombreextKeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Abreviatura.");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("Nombre extendido");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel4.setText("INGRESE UNA NUEVA MATERIA PRIMA");

        jLabel5.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
        jLabel5.setText("(hasta 70 caract.)");

        jLabel6.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
        jLabel6.setText("(hasta 10 caract.)");

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText("Si desea agregar una nueva materia prima, indique: A) Una abreviatura para la misma; B) Su nombre extendido. \n\nEjemplo.   \t   En casillero de Abreviatura: Gr    \n\t                   En casillero de Nombre extendido: Granito\n\nIntente no utilizar caracteres especiales como: | \" # $ % & / ( ) = ? @ - _ , etc.\n\nUna vez que ingrese la materia prima deseada, el sistema la guardará automáticamente de la siguiente manera: \n\nGr-Granito\n\n(el guión se coloca de forma automática).\n\nPosteriormente, podrá solicitar visualizar únicamente las siglas, o bien, las siglas más los nombres extendidos.");
        jTextArea1.setWrapStyleWord(true);
        jScrollPane3.setViewportView(jTextArea1);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton1.setText("Ingresar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(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()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(906, 906, 906))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane2)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txt_abrev, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(txt_nombreext)
                                        .addGap(18, 18, 18)
                                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(jScrollPane3))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
                .addGap(28, 28, 28)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_abrev, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_nombreext, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5))
                .addGap(29, 29, 29))
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addGap(0, 0, 0))
        );

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

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
Cargar_MP carg = new Cargar_MP();
carg.cargar_todas_mpJtable(jTable1);
    }//GEN-LAST:event_formWindowOpened

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

    }//GEN-LAST:event_txt_abrevKeyPressed

    private void txt_abrevKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_abrevKeyTyped
            char caracter = evt.getKeyChar();
        if (caracter != '-') {
            
        }else{
            evt.consume();
        }
          if (txt_abrev.getText().length()== 10){
    evt.consume();
}
    }//GEN-LAST:event_txt_abrevKeyTyped

    private void txt_nombreextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_nombreextKeyTyped
            char caracter = evt.getKeyChar();
        if (caracter != '-') {
            
        }else{
            evt.consume();
        }
          if (txt_nombreext.getText().length()== 70){
    evt.consume();
}
    }//GEN-LAST:event_txt_nombreextKeyTyped

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if ((txt_abrev.getText().length() > 0) && (txt_nombreext.getText().length() > 0)) {
            
            String nombre = txt_abrev.getText() + "-" + txt_nombreext.getText();
            InteraccionesBD inter = new InteraccionesBD();
            int id = inter.obtenersiguienteID("MP", "CODIGO_NUM");

            guardarMP(id, nombre);
        } else {
            JOptionPane.showMessageDialog(null, "Debe indicar la abreviatura y el nombre extendido de la MP para guardarla");
        }
        

    }//GEN-LAST:event_jButton1ActionPerformed

    private void eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarActionPerformed
if(jTable1.getSelectedRow()>-1){
    

        if (JOptionPane.showConfirmDialog(null, "Se desaconseja la eliminación de las materias primas, \n ya que puede "
        + "perder la información de piezas que contengan esta MP. "
        + "\n \n "
        + "\n ¿Aún así, desea eliminar la MP: " + jTable1.getValueAt(jTable1.getSelectedRow(), 0)+"?", "WARNING",
        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            String mp = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),0));
            eliminarmp(mp);
} else {
    
}   }   

        
      
    }//GEN-LAST:event_eliminarActionPerformed

   private void eliminarmp(String mp){
         int confirma =0;
  
        String sql = "DELETE FROM MP WHERE NOMBRE_MP='"+mp+"'";    
            try {
            conexion c = new conexion();
            c.getConexion();

            confirma = c.eliminar_actualizar(sql);
            c.closeconnection();
                  if(confirma>0){
         JOptionPane.showMessageDialog(null, "Se eliminó la MP: "+mp );
         Cargar_MP carg = new Cargar_MP();
        carg.cargar_todas_mpJtable(jTable1);
         
         }
    } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "No se pudo eliminar la MP: " + mp +" / "+ ex);
        }
    }
    private void guardarMP(int num, String mp){
       int respuesta=0;

        try {
            conexion c = new conexion();
            c.getConexion();
            respuesta = c.insert("insert into MP(CODIGO_NUM, "
                + "CODIGO_MP,"
                + "NOMBRE_MP"
                +") Values ("+num+","
                +"'"+String.valueOf(num)+"',"
                +"'"+mp+"'"
                + ")");

            c.closeconnection();


        } catch (SQLException ex) {
            Logger.getLogger(DT_frame.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(respuesta>0){
                   JOptionPane.showMessageDialog(null, "Se ha guardado correctamente su materia prima");
                   Cargar_MP carg = new Cargar_MP();
                    carg.cargar_todas_mpJtable(jTable1);
                    txt_abrev.setText("");
                    txt_nombreext.setText("");
                   
        }
}
    /**
     * @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(MateriasPrimas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MateriasPrimas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MateriasPrimas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MateriasPrimas.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 MateriasPrimas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem eliminar;
    private javax.swing.JButton jButton1;
    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.JLabel jLabel6;
    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.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField txt_abrev;
    private javax.swing.JTextField txt_nombreext;
    // End of variables declaration//GEN-END:variables
}
