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

import clases.copiar_tabla;
import java.awt.Toolkit;
import java.awt.datatransfer.ClipboardOwner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.*;
import java.util.Objects;
import java.util.Set;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.*;
import javax.swing.JOptionPane;
import static Filtros.Estadistica.media;
import static Filtros.Estadistica.moda;
import static Filtros.Estadistica.n_moda;
import static Filtros.Estadistica.tbl_freq;
import static Filtros.Estadistica.mediana_txt;
import static Filtros.Estadistica.intervalo;
import static Filtros.Estadistica.intervalo;
import static Filtros.Estadistica.varianzatxt;
import static Filtros.Estadistica.desviacion_txt;
import static Filtros.Estadistica.lbl_col_selec;
import arql2020.presentacion;
/**
 *
 * @author chuen
 */
public class Graficos_analisis_personalizados extends javax.swing.JFrame implements ClipboardOwner {
public static double sumatoria=0;
ArrayList<String> columnaString = new ArrayList<String>(); 
ArrayList<Integer> columnaNum = new ArrayList<Integer>(); 
public static String ventana="";
    public Graficos_analisis_personalizados() {
        initComponents();
        this.setExtendedState(MAXIMIZED_BOTH);
    }
public void setclipboard(){

DefaultTableModel dtm = (DefaultTableModel) tbl_freq.getModel();
int filas=dtm.getRowCount();
int columnas=dtm.getColumnCount();
String tablafrecuencias = "\n \n Tabla de frecuencias \n \n";

for (int i = 0; i < filas; i++) {
        for (int j = 0; j < columnas; j++) {
            String aux = String.valueOf(dtm.getValueAt(i, j));
            tablafrecuencias = tablafrecuencias + aux + ", ";
            
        }
        tablafrecuencias=tablafrecuencias+"\n";
        
    }
    

    String datos= "\nARQL_V2.0---------------------------"
            +"Media: "+media.getText()
            +"\nModa: "+moda.getText()
            +tablafrecuencias
            +"\n \nMediana: "+mediana_txt.getText()
            +"\nIntervalo: "+intervalo.getText()
            +"\nVarianza: "+varianzatxt.getText()
            +"\nDesviación estándar: "+desviacion_txt.getText();

    StringSelection txt= new StringSelection(datos);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(txt, this);
    JOptionPane.showMessageDialog(null, "Datos copiados");
}
    /**
     * 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() {

        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_person = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        Escritorio = new javax.swing.JDesktopPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tbl_person.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        tbl_person.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"tamaño1", "Andrea", "hola", "Comer", "1"},
                {"tamaño1", "Melina", "hola", "Comer", "2"},
                {"tamaño1", "Julia", "porfavor", "Dormir", "3"},
                {"tamaño2", "Andrea", "porfavor", "Comer", "4"},
                {"tamaño2", "Julia", "gracias", "Comer", "1"},
                {"tamaño2", "Mariela", "hola", "Beber", "9"}
            },
            new String [] {
                "Tamaño", "Nombre", "Pide", "Quiere", "Tiene"
            }
        ));
        tbl_person.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tbl_person.setRowHeight(25);
        tbl_person.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl_personMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tbl_person);

        jButton2.setText("Copiar tabla");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

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

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton3.setText("Media, moda, mediana, etc.");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton4.setText("Gráficos uni y bivariables");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(26, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addComponent(jButton4)
                .addGap(19, 19, 19))
        );

        jButton5.setText("Guardar tabla");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout EscritorioLayout = new javax.swing.GroupLayout(Escritorio);
        Escritorio.setLayout(EscritorioLayout);
        EscritorioLayout.setHorizontalGroup(
            EscritorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 213, Short.MAX_VALUE)
        );
        EscritorioLayout.setVerticalGroup(
            EscritorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setText("ARREGLAR ESTADISTICAS PARA VALORES DECIMALES :D\nTAMBIEN ARREGLAR ESTADISTICA PARA QUE SE VEA LA MODA");
        jScrollPane1.setViewportView(jTextArea1);

        jMenu1.setText("Ir...");

        jMenuItem1.setText("Extraer nuevas columnas");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Filtros");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("Inicio");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane2)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Escritorio))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(Escritorio)
        );

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

    private void tbl_personMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_personMouseClicked

if(ventana.equals("estadistica")){
        columnaString.clear();
        columnaNum.clear();
//analizo el tipo de dato que tiene cada col        
int tipodatocol = 0;
String cadena="";
int colselec = tbl_person.getSelectedColumn();

        for (int i = 0; i < tbl_person.getRowCount(); i++) {
            cadena=String.valueOf(tbl_person.getValueAt(i, colselec));
                if (isNumeric(cadena) == true){
                    
                }else{
                   tipodatocol=tipodatocol+1; 
                    
            }
     
        }

       

        for (int i = 0; i < tbl_person.getRowCount(); i++) {
            
            columnaString.add(String.valueOf(tbl_person.getValueAt(i, tbl_person.getSelectedColumn())));
            
            if(tipodatocol==0){
              columnaNum.add(Integer.parseInt((String) tbl_person.getValueAt(i, tbl_person.getSelectedColumn())));
            }

            
        }
              if(tipodatocol==0){
        media(columnaNum);
        moda(columnaNum);
        tabla_moda(columnaNum);
        intervalo(columnaNum);
        varianzacalc(columnaNum, media.getText());
        desviacion(varianzatxt.getText());
        medianacalc(columnaNum);
        lbl_col_selec.setText("Columna seleccionada: "+tbl_person.getColumnName(colselec));
        }else{
         lbl_col_selec.setText("Valores sólo aptos para columnas numéricas");          
        media.setText("");
        moda.setText("");
        n_moda.setText("");
        //eliminar filas de tbl_freq
        DefaultTableModel dtm = (DefaultTableModel) tbl_freq.getModel();
        int filas = dtm.getRowCount();
        for (int i = 0; filas > i; i++) {
            dtm.removeRow(0);
        }
        mediana_txt.setText("");
        intervalo.setText("");
        varianzatxt.setText("");
        desviacion_txt.setText("");
    }
        }

if(ventana.equals("grafico")){
    
    
}

    }//GEN-LAST:event_tbl_personMouseClicked

    public static boolean isNumeric(String cadena) {

        boolean resultado;

        try {
            Float.parseFloat(cadena);
            resultado = true;
        } catch (NumberFormatException excepcion) {
            resultado = false;
        }

        return resultado;
    }    
    
private void medianacalc(ArrayList<Integer> conjunto){
 Collections.sort(conjunto);

int mediana;
int mitad = conjunto.size() / 2;
// Si la longitud es par, se deben promediar los del centro
if (conjunto.size() % 2 == 0) {
    mediana = ((conjunto.get(mitad - 1) + conjunto.get(mitad))/2);
} else {
    mediana = conjunto.get(mitad);
}

mediana_txt.setText(String.valueOf(mediana));
}
    
    private void varianzacalc(ArrayList<Integer> conjunto, String mediax){

double mediaf = Double.parseDouble(mediax);
double[]valor = new double[1];
double varianza=0;

    for (int i = 0; i < conjunto.size(); i++) {
         valor[0]= (double) conjunto.get(i);
        sumatoria= Math.pow(valor[0]-mediaf, 2);
        varianza=varianza+sumatoria;
        
    }
    varianza=varianza/(conjunto.size()-1);
    varianzatxt.setText(String.valueOf(varianza));
}
private void desviacion(String varianzax){


double varianzad= Double.parseDouble(varianzax) ;
double desviacion = 0;
desviacion = Math.sqrt(varianzad);

desviacion_txt.setText(String.valueOf(desviacion));
}
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
DefaultTableModel modelo = (DefaultTableModel) tbl_person.getModel();
copiar_tabla copiartab = new copiar_tabla();
copiartab.copiartabla(modelo);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
ventana="estadistica";
Escritorio.removeAll();
Estadistica est = new  Estadistica();
Escritorio.add(est);
est.show();       
       
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
ventana="grafico";
Escritorio.removeAll();
Graficos graf = new Graficos();
Escritorio.add(graf);
graf.show();       
       
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        presentacion pres = new presentacion();
        pres.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
seleccionar_columnas selec = new seleccionar_columnas();
selec.setVisible(true);
this.dispose();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
Filtros_frame filt = new Filtros_frame();
filt.setVisible(true);
this.dispose();
    }//GEN-LAST:event_jMenuItem2ActionPerformed
private void media(ArrayList<Integer> conjunto){
float promedio = 0;    
    for (int i = 0; i < conjunto.size(); i++) {
        promedio = promedio + conjunto.get(i);
    }
    promedio=promedio/conjunto.size();
    media.setText(String.valueOf(promedio));
}
private void intervalo(ArrayList<Integer> conjunto){
float max = Collections.max(conjunto);
float min = Collections.min(conjunto);
intervalo.setText(String.valueOf(max-min));
}

private void moda(ArrayList<Integer> conjunto){

int maximaVecesQueSeRepite = 0;
int modax = 0;

for(int i=0; i<conjunto.size(); i++){
int vecesQueSeRepite = 0;
for(int j=0; j<conjunto.size(); j++){
if(conjunto.get(i) == conjunto.get(j)){
vecesQueSeRepite++;
}
if(vecesQueSeRepite > maximaVecesQueSeRepite){
modax = conjunto.get(i);
maximaVecesQueSeRepite = vecesQueSeRepite;

}
}
}

     moda.setText(String.valueOf(modax));
    n_moda.setText(String.valueOf(maximaVecesQueSeRepite));   

}
private void tabla_moda(ArrayList<Integer> conjunto){
DefaultTableModel dtm = (DefaultTableModel) tbl_freq.getModel();
            int filas=dtm.getRowCount();
            for (int i = 0;filas>i; i++) {
                dtm.removeRow(0);
            }
    
ArrayList<Integer> conjuntodisctint = new ArrayList<>();

    for (int i = 0; i < conjunto.size(); i++) {
        conjuntodisctint.add(conjunto.get(i));
    }
    Set<Integer> hashSet = new HashSet<Integer>(conjuntodisctint);
        conjuntodisctint.clear();
        conjuntodisctint.addAll(hashSet);
int contador=0;

String [] fila = new String[2];


        
        for (int i = 0; i < conjuntodisctint.size(); i++) {

            for (int j = 0; j < conjunto.size(); j++) {
                 if(conjuntodisctint.get(i)== conjunto.get(j)){
                 
                     fila[0]=String.valueOf(conjuntodisctint.get(i));
                     contador = contador+1;
                }
                
            }
                fila[1]=String.valueOf(contador);
                dtm.addRow(fila);
                contador=0;
               
    }
        
 TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tbl_freq.getModel());
tbl_freq.setRowSorter(sorter);

List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
sortKeys.add(new RowSorter.SortKey(1, SortOrder.DESCENDING));
sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);  
        
}


    /**
     * @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(Graficos_analisis_personalizados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Graficos_analisis_personalizados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Graficos_analisis_personalizados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Graficos_analisis_personalizados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

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

}
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDesktopPane Escritorio;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    public static javax.swing.JTable tbl_person;
    // End of variables declaration//GEN-END:variables

    @Override
    public void lostOwnership(Clipboard clipboard, Transferable contents) {
       //To change body of generated methods, choose Tools | Templates.
    }
}
