/*
 * jVentana.java
 *
 * Created on 22 de octubre de 2006, 15:15
 */

package dectecmovimiento;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.Image;
import java.io.File;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import javax.swing.Timer;


/**
 *
 * @author  Robotica
 */
public class jVentana extends javax.swing.JFrame implements Runnable {
    
    /** Creates new form jVentana */
    private File leeImagen1, leeImagen2;
    private Graphics2D grafico;
    private Timer clock;
    private int count_imagenes = 32;
    
    public jVentana() {
        initComponents();
        jLabel1.setText("");
        jSlider1.setMinimum(0);
        jSlider1.setMaximum(150);
        jPrueba.setText("");
        jLabel3.setText("");
        jControlMovimiento.setText("");
        
        memImagenes = new File[count_imagenes];
        
        /*HEBRA DESTINADA A REGRAFICAR Y CALCULAR LOS VALORES DEL UMBRAL PARA 
        LA CODIFICACION DE LA IMAGEN EN EL RANGO DE BLANCO Y NEGRO */
        t = new Thread(this);

        try {               
            memImagenes[0] = new File("imagenes/bono_1.jpg");
            memImagenes[1] = new File("imagenes/bono_2.jpg");
            memImagenes[2] = new File("imagenes/bono_3.jpg");
            memImagenes[3] = new File("imagenes/bono_4.jpg");            
            memImagenes[4] = new File("imagenes/bono_5.jpg");
            memImagenes[5] = new File("imagenes/bono_6.jpg");
            memImagenes[6] = new File("imagenes/bono_7.jpg");
            memImagenes[7] = new File("imagenes/bono_8.jpg");
            memImagenes[8] = new File("imagenes/bono_9.jpg");            
            memImagenes[9] = new File("imagenes/bono_10.jpg");
            memImagenes[10] = new File("imagenes/bono_11.jpg");
            memImagenes[11] = new File("imagenes/bono_12.jpg");
            memImagenes[12] = new File("imagenes/bono_13.jpg");
            memImagenes[13] = new File("imagenes/bono_14.jpg");
            memImagenes[14] = new File("imagenes/bono_15.jpg");
            memImagenes[15] = new File("imagenes/bono_16.jpg");
            memImagenes[16] = new File("imagenes/bono_17.jpg");            
            memImagenes[17] = new File("imagenes/bono_18.jpg");
            memImagenes[18] = new File("imagenes/bono_19.jpg");
            memImagenes[19] = new File("imagenes/bono_20.jpg");
            memImagenes[20] = new File("imagenes/bono_21.jpg");
            memImagenes[21] = new File("imagenes/bono_22.jpg");            
            memImagenes[22] = new File("imagenes/bono_23.jpg");
            memImagenes[23] = new File("imagenes/bono_24.jpg");
            memImagenes[24] = new File("imagenes/bono_25.jpg");
            memImagenes[25] = new File("imagenes/bono_26.jpg");
            memImagenes[26] = new File("imagenes/bono_27.jpg");
            memImagenes[27] = new File("imagenes/bono_28.jpg");
            memImagenes[28] = new File("imagenes/bono_29.jpg");
            memImagenes[29] = new File("imagenes/bono_30.jpg");            
            memImagenes[30] = new File("imagenes/bono_31.jpg");
            memImagenes[31] = new File("imagenes/bono_32.jpg");
            
            Imagenes1 = ImageIO.read(memImagenes[INDICE]);
            Imagenes2 = ImageIO.read(memImagenes[INDICE + 1]);

            System.out.println("Imagen leida");
       
        } catch (Exception e) {
          System.out.println("No se pudo cargar la imagen ");
          System.exit(0);
        }
        
        img_1 = this.scalGrey(Imagenes1);
        img_2 = this.scalGrey(Imagenes2);
        temp = new BufferedImage(img_1.getWidth(), img_1.getHeight(), img_1.getType());
        
        clock = new Timer(10, new ActionListener(){
             synchronized public void actionPerformed(ActionEvent e) {
                 
                INDICE = (INDICE + 1) % count_imagenes;
                try {
                // TODO add your handling code here:
                    Imagenes1 = ImageIO.read(memImagenes[INDICE]);
                    Imagenes2 = ImageIO.read(memImagenes[(INDICE + 1) % count_imagenes]);

                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                    //DETERMINACION DE AMBAS IMAGENES EN NIVEL DE GRIS
                    img_1 = scalGrey(Imagenes1);
                    img_2 = scalGrey(Imagenes2);
                    diferenMatriz(jSlider1.getValue());
  
                    
                    paint(getGraphics());
                    //jPanel1.repaint();
                    repaint();
             }
            });

        Imax = img_1.getWidth();
        Jmax = img_1.getHeight();
        
        jSlider1.setValue(jSlider1.getMaximum()/2);
        paint(jPanel1.getGraphics());
        
        
            diferenMatriz(jSlider1.getValue());
        //CORRE LA HEBRA ENCARGADA DE GRAFICAR EL jSlider1....
        t.start();
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jPrueba = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jControlMovimiento = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(249, 248, 246));
        jPanel1.setLayout(null);

        jPanel1.setBackground(new java.awt.Color(230, 230, 230));
        jButton1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jButton1.setText("INICIAR");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
            }
        });

        jPanel1.add(jButton1);
        jButton1.setBounds(660, 340, 200, 80);

        jLabel1.setBackground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("jLabel1");
        jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.orange, new java.awt.Color(255, 128, 0), java.awt.Color.orange, java.awt.Color.orange));
        jLabel1.setOpaque(true);
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 40, 560, 360);

        jSlider1.setBackground(new java.awt.Color(255, 241, 235));
        jSlider1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jSlider1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jSlider1MouseDragged(evt);
            }
        });

        jPanel1.add(jSlider1);
        jSlider1.setBounds(20, 440, 310, 20);

        jPrueba.setText("jTextField1");
        jPrueba.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.add(jPrueba);
        jPrueba.setBounds(350, 430, 70, 30);

        jLabel3.setBackground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("jLabel3");
        jLabel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.red, java.awt.Color.red));
        jLabel3.setOpaque(true);
        jPanel1.add(jLabel3);
        jLabel3.setBounds(620, 40, 260, 180);

        jControlMovimiento.setText("jTextField1");
        jPanel1.add(jControlMovimiento);
        jControlMovimiento.setBounds(800, 230, 80, 30);

        jButton3.setText("SUAVIZADO");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton3MousePressed(evt);
            }
        });

        jPanel1.add(jButton3);
        jButton3.setBounds(620, 230, 160, 40);

        jTabbedPane1.addTab("tab1", jPanel1);

        jMenu1.setText("Menu");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Menu");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("Menu");
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 915, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MousePressed
    // TODO add your handling code here:
       temp = mMascara(temp);
       paint(getGraphics());
       //jPanel1.repaint();
       repaint(); 
        
        
    }//GEN-LAST:event_jButton3MousePressed
   
    private void jSlider1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MouseDragged
    // TODO add your handling code here:
        String valor = null;
        jPrueba.setText(valor.valueOf(jSlider1.getValue()));

    }//GEN-LAST:event_jSlider1MouseDragged

    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MousePressed
        
        if(ESTADO_ON_OFF == false){
            clock.start();
            jButton1.setText("DETENER");
            ESTADO_ON_OFF = true;
        }
        else
            if(ESTADO_ON_OFF == true){
                clock.stop();
                jButton1.setText("INICIAR");
                ESTADO_ON_OFF = false;
            }
       
            
    }//GEN-LAST:event_jButton1MousePressed
  
    
    public void diferenMatriz(int umBral){
        Color a1, b1, c1;
        int colorTemp = 0;
        int movimiento = 0;
        String paso = null;
        
        for(int i=0; i < Imax; i++)
            for(int j=0; j < Jmax; j++){
                a1 = new Color(img_1.getRGB(i, j));
                b1 = new Color(img_2.getRGB(i, j));
                colorTemp = Math.abs(a1.getRed() - b1.getRed());
                if(colorTemp < 5) colorTemp = 255;
                    else colorTemp = b1.getRed();
                
                if(colorTemp > umBral) c1 = new Color(255, 255, 255);
                else{
                    movimiento = movimiento + 1;
                    c1 = new Color(0,0,0);
                }
                temp.setRGB(i,j, c1.getRGB());
            }
        jControlMovimiento.setText(paso.valueOf(movimiento));
        movimiento = 0;
    }
    
    public BufferedImage scalGrey(BufferedImage imaRGB){
        BufferedImage imaReturn = new BufferedImage(imaRGB.getWidth(), imaRGB.getHeight(), imaRGB.getType());
        Color a1, b1;
        int promedio = 0;
        
            for(int i=0; i < imaRGB.getWidth(); i++)
                for(int j=0; j < imaRGB.getHeight(); j++){
                    a1 = new Color(imaRGB.getRGB(i, j));
                    promedio = Math.abs((a1.getRed() + a1.getGreen() + a1.getBlue())/3);
                    b1 = new Color(promedio, promedio, promedio);
                    imaReturn.setRGB(i,j, b1.getRGB());
            }      
        return(imaReturn);
    }
    
    public void paint(Graphics g){
        jLabel1.setIcon(new ImageIcon(((Image)Imagenes2).getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), Imagenes2.SCALE_FAST))); //imagenes/bono1.jpg"));
        jLabel3.setIcon(new ImageIcon(((Image)temp).getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), temp.SCALE_FAST))); //imagenes/bono1.jpg"));
        super.paint(g);
    }
    
    
    
    public BufferedImage mMascara(BufferedImage iFiltrar){
         
         Color a1, b1;
         int resultado_suma = 0;
         int movimiento = 0;
         String paso = null;
         
         BufferedImage imaReturn = new BufferedImage(iFiltrar.getWidth(), iFiltrar.getHeight(), iFiltrar.getType());
         
         for(int i=1; i < iFiltrar.getWidth()-1; i++)
            for(int j=1; j < iFiltrar.getHeight()-1; j++){
                    for(int x=i-1; x < i+2; x++ )
                        for(int y=j-1; y < j+2; y++){
                            a1 = new Color(iFiltrar.getRGB(x, y));
                            resultado_suma = resultado_suma + a1.getRed();                
                        }                     
                     resultado_suma = resultado_suma / 9;
                     if(resultado_suma > 128)
                         resultado_suma = 255;
                     else {
                           resultado_suma = 0;
                           movimiento = movimiento + 1;
                           
                     }       
                     
                     b1 = new Color(resultado_suma, resultado_suma, resultado_suma);           
                     imaReturn.setRGB(i,j, b1.getRGB());
                     resultado_suma = 0;
            }
        jControlMovimiento.setText(paso.valueOf(movimiento)); 
        return(imaReturn);
    }

    
    public void run(){
        while(true){
            jPanel1.repaint();
        
        try {
            t.sleep((long)250);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            }  
        }
        
    }
     /**
     * @param args the command line arguments
     
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jVentana().setVisible(true);
                
            }
        });
    }*/
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JTextField jControlMovimiento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    public javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jPrueba;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables
    private BufferedImage img_1 = null;
    private BufferedImage img_2 = null;
    private BufferedImage Imagenes1, Imagenes2;
    private BufferedImage img_1Temp = null;
    private BufferedImage img_2Temp = null;
    private BufferedImage usuar = null;
    public  BufferedImage temp = null;
    private int INDICE=0;
    private int Imax = 0;
    private int Jmax = 0;
    private File[] memImagenes;
    private Thread t;
    private boolean ESTADO_ON_OFF = false;
}

/*
    public BufferedImage rangoUmbral(BufferedImage umTemp, int umBral){
        BufferedImage imaReturn = new BufferedImage(umTemp.getWidth(), umTemp.getHeight(), umTemp.getType());
        Color a1, b1;
        
        for(int i=0; i < Imax; i++)
            for(int j=0; j < Jmax; j++){
                a1 = new Color(umTemp.getRGB(i,j));
                if(a1.getRed() > 128) b1 = new Color(255,255,255);
                else b1 = new Color(a1.getRed(), a1.getRed(), a1.getRed());
                imaReturn.setRGB(i, j, b1.getRGB());
            }
         return(imaReturn);
    }
 
    public void laplaciano(){
        
        int suma  =  0;
        Color a, b; 

        for(int i=1; i < (Imax-1); i++)
            for(int j=1; j < (Jmax-1); j++){

                suma = -1*(new Color(temp.getRGB(i - 1, j - 1))).getBlue() -
                       (new Color(temp.getRGB(i, j - 1))).getBlue() -
                       (new Color(temp.getRGB(i + 1, j - 1))).getBlue() - 
                       (new Color(temp.getRGB(i - 1, j))).getBlue() +
                       8*(new Color(temp.getRGB(i, j))).getBlue() -
                       (new Color(temp.getRGB(i + 1, j))).getBlue() -
                       (new Color(temp.getRGB(i - 1, j + 1))).getBlue() - 
                       (new Color(temp.getRGB(i, j + 1))).getBlue() -
                       (new Color(temp.getRGB(i + 1, j + 1))).getBlue() ;
                       
                       if(suma > 50){
                           b = new Color(0,0,0);
                           temp.setRGB(i,j,b.getRGB());
                       }
                       else{                       
                           b = new Color(255,255,255);
                           temp.setRGB(i,j,b.getRGB());
                       }
            }
    }
  */