/*
 * 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 arql2020.ARQL2020;
import static arql2020.ARQL2020.WHERE;
import clases.InteraccionesBD;
import clases.conexion;
import java.awt.BorderLayout;
import java.awt.Color;
import java.beans.PropertyVetoException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author chuen
 */
public class K_Combinacion_grupos extends javax.swing.JInternalFrame {

    /**
     * Creates new form F_Formatizacion_utiles1
     */
    public K_Combinacion_grupos() {
        initComponents();
                    try {
            this.setMaximum(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(B_Composicion_puntasfilossup.class.getName()).log(Level.SEVERE, null, ex);
        }


        
    }

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

        botones1 = new javax.swing.ButtonGroup();
        botones2 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbx_grupos = new javax.swing.JComboBox<>();
        jScrollPane5 = new javax.swing.JScrollPane();
        tbl = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        cbx_mp = new javax.swing.JComboBox<>();
        jButton3 = new javax.swing.JButton();
        btn_calcular = new javax.swing.JButton();
        jLabel15 = new javax.swing.JLabel();
        txt_muestra = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        txt_sentencia = new javax.swing.JTextField();
        jLabel27 = new javax.swing.JLabel();
        txt_mp_selec = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        btn_info = new javax.swing.JButton();
        btn_arbol = new javax.swing.JButton();
        btn_copiar = new javax.swing.JButton();
        txt_diversidad = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        tbl1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        btn_copiar1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txt_grupodoble = new javax.swing.JTextArea();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Combinación de grupos tipológicos");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Grupos tipológicos presentes");

        cbx_grupos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbx_grupos.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbx_gruposItemStateChanged(evt);
            }
        });

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

            },
            new String [] {
                "ARQ:L GENERAL", "ARQ:L SEGMENTAL ESTANDAR", "GRUPO TIPOLÓGICO"
            }
        ));
        tbl.setGridColor(new java.awt.Color(255, 51, 51));
        tbl.setRowHeight(25);
        jScrollPane5.setViewportView(tbl);
        if (tbl.getColumnModel().getColumnCount() > 0) {
            tbl.getColumnModel().getColumn(0).setHeaderValue("ARQ:L GENERAL");
            tbl.getColumnModel().getColumn(1).setHeaderValue("ARQ:L SEGMENTAL ESTANDAR");
            tbl.getColumnModel().getColumn(2).setHeaderValue("GRUPO TIPOLÓGICO");
        }

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Materia prima ");

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

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton3.setText("MP PRESENTES EN LA MUESTRA");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        btn_calcular.setBackground(new java.awt.Color(204, 255, 0));
        btn_calcular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/lentes.png"))); // NOI18N
        btn_calcular.setToolTipText("Realizar análisis");
        btn_calcular.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                btn_calcularComponentHidden(evt);
            }
        });
        btn_calcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_calcularActionPerformed(evt);
            }
        });

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel15.setText("Cálculo realizado sobre muestra:");

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

        jLabel16.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel16.setText("Sentencia:");

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

        jLabel27.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel27.setText("Materia prima:");

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

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("Piezas donde se encuentra presente el grupo tipológico seleccionado");

        btn_info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/info.png"))); // NOI18N
        btn_info.setToolTipText("Información sobre el análisis");
        btn_info.setEnabled(false);
        btn_info.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_infoActionPerformed(evt);
            }
        });

        btn_arbol.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/arbol.png"))); // NOI18N
        btn_arbol.setToolTipText("Arbol: CLASES ARTEFACTUALES PRESENTES EN LA MP SELECCIONADA");
        btn_arbol.setEnabled(false);
        btn_arbol.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_arbolActionPerformed(evt);
            }
        });

        btn_copiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/copiar.png"))); // NOI18N
        btn_copiar.setToolTipText("Copiar valores en el portapapeles");
        btn_copiar.setEnabled(false);
        btn_copiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_copiarActionPerformed(evt);
            }
        });

        txt_diversidad.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        txt_diversidad.setText("Diversidad presente");

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

            },
            new String [] {
                "Diversidad de grupos tipológicos"
            }
        ));
        tbl1.setGridColor(new java.awt.Color(255, 51, 51));
        tbl1.setRowHeight(25);
        jScrollPane6.setViewportView(tbl1);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton1.setText("Ver piezas que contienen este grupo");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btn_copiar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/copiar.png"))); // NOI18N
        btn_copiar1.setToolTipText("Copiar valores en el portapapeles");
        btn_copiar1.setEnabled(false);
        btn_copiar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_copiar1ActionPerformed(evt);
            }
        });

        txt_grupodoble.setColumns(20);
        txt_grupodoble.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        txt_grupodoble.setLineWrap(true);
        txt_grupodoble.setRows(5);
        txt_grupodoble.setWrapStyleWord(true);
        jScrollPane2.setViewportView(txt_grupodoble);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(btn_calcular, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jLabel15))
                                .addComponent(jLabel27))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(txt_muestra, javax.swing.GroupLayout.PREFERRED_SIZE, 501, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jLabel16)
                                    .addGap(201, 201, 201))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(btn_info, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(btn_arbol, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGap(45, 45, 45))
                                        .addComponent(txt_mp_selec))
                                    .addGap(40, 40, 40))))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txt_sentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(cbx_mp, javax.swing.GroupLayout.PREFERRED_SIZE, 675, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(40, 40, 40)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cbx_grupos, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 1012, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_copiar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txt_diversidad)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 1012, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btn_copiar1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(39, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbx_mp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(42, 42, 42)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_calcular, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel15)
                        .addComponent(txt_sentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel16)
                        .addComponent(txt_muestra, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_mp_selec, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel27))
                .addGap(35, 35, 35)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbx_grupos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1))
                    .addComponent(btn_info, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_arbol, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_copiar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37)
                .addComponent(txt_diversidad)
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btn_copiar1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2)))
                .addContainerGap(102, 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.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1305, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1129, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );

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

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if(WHERE.equals("")){
            JOptionPane.showMessageDialog(null, "Debe seleccionar una muestra previamente");
        }else{
            CalculosBD calc = new CalculosBD();
            calc.cargarmpformdistinct(cbx_mp, WHERE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void btn_calcularComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_btn_calcularComponentHidden
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_calcularComponentHidden

    private void btn_calcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_calcularActionPerformed
        if(cbx_mp.getSelectedIndex()==0){
            JOptionPane.showMessageDialog(null, "Seleccione previamente una materia prima");
        }else{

            txt_muestra.setText(ARQL2020.etiqueta_muestra);
            txt_sentencia.setText(ARQL2020.WHERE);
            txt_mp_selec.setText(cbx_mp.getSelectedItem().toString());

            
            obtenergrupos();
             jButton1.setEnabled(true);
            DefaultTableModel dtm = (DefaultTableModel) tbl.getModel();
            int filas = dtm.getRowCount();
            for (int i = 0; filas > i; i++) {
                dtm.removeRow(0);
                
               
            }
            btn_copiar.setEnabled(true);
            btn_copiar1.setEnabled(true);
   
        }
    }//GEN-LAST:event_btn_calcularActionPerformed
private void obtenergrupos(){
 cbx_grupos.removeAllItems();
 cbx_grupos.addItem("Grupos tipológicos presentes");
String grupo = new String();
ResultSet rs = null;
String consulta = "SELECT  DISTINCT(s.GRUPO)  FROM  SEGMENTAL_ESTANDAR2 s \n"  +
        "INNER JOIN \n" +
"FORMATIZADOS f  \n" +
"ON f.ID_FORMATIZADOS = s.ID_FORMATIZADOS " 
        +txt_sentencia.getText() + " AND (f.MP='"+txt_mp_selec.getText()+"')  " ;
             try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);
         
             
               while(rs.next()){
                grupo=rs.getString("GRUPO");
                cbx_grupos.addItem(grupo);
               
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }

 consulta = "SELECT  COUNT(*)  FROM  NUCLEOS s \n"  +
        "INNER JOIN \n" +
"FORMATIZADOS f  \n" +
"ON f.ID_FORMATIZADOS = s.ID_FORMATIZADOS " 
        +txt_sentencia.getText() + " AND (f.MP='"+txt_mp_selec.getText()+"')  " ;
             try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);
         
             
               if(rs.next()){
                cbx_grupos.addItem("Nu-Núcleo");
               
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
 consulta = "SELECT  COUNT(*)  FROM  PUNTAS_DE_PROYECTIL2 s \n"  +
        "INNER JOIN \n" +
"FORMATIZADOS f  \n" +
"ON f.ID_FORMATIZADOS = s.ID_FORMATIZADOS " 
        +txt_sentencia.getText() + " AND (f.MP='"+txt_mp_selec.getText()+"')  " ;
             try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);
         
             
               if(rs.next()){
                cbx_grupos.addItem("PP-Punta de proyectil");
               
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
}
    private void btn_infoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_infoActionPerformed
        String analisis = "";
        info_frame info = new info_frame();
        info.setVisible(true);
        info.info_procedencia.setText("MUESTRA---->" + txt_muestra.getText() +"\n SENTENCIA---->" +txt_sentencia.getText() );
        info.info_mp.setText(txt_mp_selec.getText());
        info.info_analisis.setText(analisis);
    }//GEN-LAST:event_btn_infoActionPerformed

    private void btn_arbolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_arbolActionPerformed
arbol();        
    }//GEN-LAST:event_btn_arbolActionPerformed
private void arbol (){
    Arbol ar = new Arbol();
ar.setVisible(true);
 ar.txt_mp.setText(txt_mp_selec.getText());
 
 DiseñoArbol d = new DiseñoArbol(txt_sentencia.getText(), txt_mp_selec.getText());
DefaultTreeModel model = (DefaultTreeModel) ar.arbol_analisis_FORM.getModel();        
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    
String sentencia = txt_sentencia.getText();
String matprim = txt_mp_selec.getText();


   ArrayList<Integer> ids_arbol = idstabla();

    DefaultMutableTreeNode hoja_categoriaA = d.armarcarpetaconpiezas(ids_arbol, "Combinados con:"+cbx_grupos.getSelectedItem().toString());
    root.add(hoja_categoriaA);
    root.setUserObject(txt_muestra.getText()+"/ "+txt_mp_selec.getText());
    ar.arbol_analisis_FORM.setModel(model);
    model.reload();
    
}

private ArrayList<Integer> idstabla(){
    ArrayList<Integer> ids_arbol = new ArrayList<>();
     DefaultTableModel dtm = (DefaultTableModel) tbl.getModel(); 
     
     for (int i = 0; i < dtm.getRowCount(); i++) {
        String codigo = dtm.getValueAt(i, 0).toString();
        String [] split = codigo.split("-");
        int aux = Integer.parseInt(split[1]);
        ids_arbol.add(aux);
    }
     
        Set<Integer> hashSet = new HashSet<Integer>(ids_arbol);
        ids_arbol.clear();
        ids_arbol.addAll(hashSet);
    
    return ids_arbol;
}
    private void btn_copiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_copiarActionPerformed
        Copiartabla copy = new Copiartabla();
        copy.copiartabla(tbl, txt_muestra.getText(), WHERE,
                "Lista de piezas que contienen el grupo "+cbx_grupos.getSelectedItem().toString()+" - Nota: se detallan los códigos de las fichas generales, y los de sus fichas asociadas (seg. estándar, de puntas de proy. o núcleos)", "Materia prima: "
                                +txt_mp_selec.getText());
    }//GEN-LAST:event_btn_copiarActionPerformed

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
  CalculosBD c = new CalculosBD();
c.cargarmp(cbx_mp); 
    }//GEN-LAST:event_formInternalFrameOpened

    private void cbx_gruposItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbx_gruposItemStateChanged

    }//GEN-LAST:event_cbx_gruposItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
   if(cbx_grupos.getSelectedIndex()==0){
    
}else{
    if(cbx_grupos.getSelectedItem().toString().equals("PP-Punta de proyectil")){
        distinct_IDFORM( "PUNTAS_DE_PROYECTIL2 ", "");
    }else{
        if(cbx_grupos.getSelectedItem().toString().equals("Nu-Núcleo")){
            distinct_IDFORM( "NUCLEOS ", "");
    }else{
            distinct_IDFORM( "SEGMENTAL_ESTANDAR2 ", " AND (s.GRUPO='"+cbx_grupos.getSelectedItem().toString()+"') ");
            }
    }
    cargartbl1();
}
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btn_copiar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_copiar1ActionPerformed
   
                   Copiartabla copy = new Copiartabla();
        copy.copiartabla(tbl1, txt_muestra.getText(), WHERE,
                "Grupos tipológicos asociados a "+cbx_grupos.getSelectedItem().toString(), "Materia prima: "
                                +txt_mp_selec.getText());
    }//GEN-LAST:event_btn_copiar1ActionPerformed
private void distinct_IDFORM(String tabla, String and){
  DefaultTableModel dtm = (DefaultTableModel) tbl.getModel();  
     int filas=dtm.getRowCount();
            for (int i = 0;filas>i; i++) {
                dtm.removeRow(0);
            }
            
            
ArrayList<Integer> grupo = new ArrayList<>();
ResultSet rs = null;
String consulta = "SELECT  DISTINCT(s.ID_FORMATIZADOS)  FROM  "+tabla+" s \n"  +
        "INNER JOIN \n" +
"FORMATIZADOS f  \n" +
"ON f.ID_FORMATIZADOS = s.ID_FORMATIZADOS " 
        +txt_sentencia.getText() + " AND (f.MP='"+txt_mp_selec.getText()+"')  " + and ;
             try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);
         
             
               while(rs.next()){
                int aux=rs.getInt("ID_FORMATIZADOS");
                grupo.add(aux);
               
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }


DiseñoArbol d = new DiseñoArbol(txt_sentencia.getText(), txt_mp_selec.getText());
d.cargarfilacombinacionesdegrupos(grupo, dtm);
}

private void cargartbl1(){
    txt_diversidad.setText("Diversidad de grupos tipológicos combinados con "+ cbx_grupos.getSelectedItem().toString());
     DefaultTableModel dtm = (DefaultTableModel) tbl.getModel();     
     DefaultTableModel dtm1 = (DefaultTableModel) tbl1.getModel();  
    
    int filas=dtm1.getRowCount();
            for (int i = 0;filas>i; i++) {
                dtm1.removeRow(0);
            }
              
    
    
  ArrayList<String> grupos = new ArrayList<>();
  ArrayList<String []> id_grupos = new ArrayList<>();
  Object gruporepetido = cbx_grupos.getSelectedItem();
boolean combinado = false;
   
         for (int i = 0; i < dtm.getRowCount(); i++) {
        String codigo = dtm.getValueAt(i, 2).toString();
       
        grupos.add(codigo);
    }
     
        Set<String> hashSet = new HashSet<String>(grupos);
        grupos.clear();
        grupos.addAll(hashSet);
    
         for (int i = 0; i < dtm.getRowCount(); i++) {
        String []id_grupo = new String[2];
        id_grupo[0]=dtm.getValueAt(i, 0).toString();
        id_grupo[1]=dtm.getValueAt(i, 2).toString();
        id_grupos.add(id_grupo);
    }
         for (int i = 0; i < id_grupos.size(); i++) {
         for (int j = 0; j < id_grupos.size(); j++) {
             if(i==j){
                 
             }else{
                 String [] valor = id_grupos.get(i);
                 String [] valor2 = id_grupos.get(j);
                 if(((valor[0].equals(valor2[0]))&&(valor[1].equals(valor2[1])))&&(i!=j)){
                    combinado=true;
                    
                 }
             }
         }
        
    }
    
        for (int i = 0; i < grupos.size(); i++) {
        if(grupos.get(i).equals(gruporepetido)){
            grupos.remove(i);
        }
        }
        if(combinado==true){
            grupos.add(gruporepetido.toString());
            txt_grupodoble.setText("Hay mas de un/a: "+ gruporepetido +" en el mismo ejemplar");
        }else{
            txt_grupodoble.setText("No hay más de un/a: "+ gruporepetido +" en el mismo ejemplar");
        }

        for (int i = 0; i < grupos.size(); i++) {
        Object []grupo = new Object[1];
        grupo[0]=grupos.get(i);
        dtm1.addRow(grupo);
    }
    
}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup botones1;
    private javax.swing.ButtonGroup botones2;
    private javax.swing.JButton btn_arbol;
    private javax.swing.JButton btn_calcular;
    private javax.swing.JButton btn_copiar;
    private javax.swing.JButton btn_copiar1;
    private javax.swing.JButton btn_info;
    private javax.swing.JComboBox<String> cbx_grupos;
    private javax.swing.JComboBox<String> cbx_mp;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel27;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTable tbl;
    private javax.swing.JTable tbl1;
    private javax.swing.JLabel txt_diversidad;
    private javax.swing.JTextArea txt_grupodoble;
    private javax.swing.JTextField txt_mp_selec;
    private javax.swing.JTextField txt_muestra;
    private javax.swing.JTextField txt_sentencia;
    // End of variables declaration//GEN-END:variables
}
