/*
 * PainelFerramentaSimulacao.java
 *
 * Created on 18 de Dezembro de 2008, 18:43
 */

package ambienteGrafico.componentes;

import algoritmo.Agente;
import algoritmo.ConjuntoDeAgentes;
import algoritmo.EspacoDeBusca;
import algoritmo.SensorFotografico;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author  Marília
 */
public class PainelFerramentaSimulacao extends MeuPainel{

    private Canvas canvas = null;
    /** Creates new form PainelFerramentaSimulacao */
    public PainelFerramentaSimulacao(Canvas canvas) {
        super.mudarLookAndFeel();
        initComponents();
        this.canvas = canvas;
    }

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

        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        bt_Simular = new MyJButton(); ;
        bt_VerMapaResultado = new MyJButton(); ;
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        tf_PorcentagemMinCompleta = new javax.swing.JTextField();
        tf_NumMaxCiclos = new javax.swing.JTextField();
        tf_IntervaloVerificacao = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        bt_AnimacaoConfig = new javax.swing.JButton();

        String[] stringComboBox = new String[] { "Estabilizar Swarm", "Alcançar Alvo", "Explorar Ambiente", "Executar PSO"};
        DefaultComboBoxModel model = new DefaultComboBoxModel(stringComboBox);
        jComboBox1.setModel(model);
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Modo de simulação");

        bt_Simular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/IconePlaySimular.png"))); // NOI18N
        bt_Simular.setToolTipText("Adicionar Alvo");
        bt_Simular.setIconTextGap(0);
        bt_Simular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_SimularActionPerformed(evt);
            }
        });

        bt_VerMapaResultado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/IconeAlvoFlexa.gif"))); // NOI18N
        bt_VerMapaResultado.setToolTipText("Adicionar Alvo");
        bt_VerMapaResultado.setIconTextGap(0);
        bt_VerMapaResultado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_VerMapaResultadoActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Condições de parada", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 0))); // NOI18N

        jLabel2.setText("Num Max Ciclos:");

        tf_PorcentagemMinCompleta.setText("75");
        tf_PorcentagemMinCompleta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_PorcentagemMinCompletaActionPerformed(evt);
            }
        });

        tf_NumMaxCiclos.setText("4000");
        tf_NumMaxCiclos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_NumMaxCiclosActionPerformed(evt);
            }
        });

        tf_IntervaloVerificacao.setText("1000");
        tf_IntervaloVerificacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_IntervaloVerificacaoActionPerformed(evt);
            }
        });

        jLabel3.setText("Intervalo Verif:");

        jLabel4.setText("% Min Completa:");

        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)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tf_PorcentagemMinCompleta, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tf_IntervaloVerificacao, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(tf_NumMaxCiclos, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGap(2, 2, 2))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(tf_IntervaloVerificacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(tf_NumMaxCiclos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_PorcentagemMinCompleta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        bt_AnimacaoConfig.setText("Config. Animação");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(bt_Simular, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_VerMapaResultado, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(20, 20, 20))
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(bt_AnimacaoConfig)
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bt_Simular)
                    .addComponent(bt_VerMapaResultado, 0, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_AnimacaoConfig)
                .addGap(326, 326, 326))
        );
    }// </editor-fold>//GEN-END:initComponents

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

        if(!bt_Simular.getActionCommand().equalsIgnoreCase("Pausar")){
              canvas.startAnimation();
              bt_Simular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/IconePauseSimular.png")));
              bt_Simular.setActionCommand("Pausar");
        }
        else{
              canvas.stopAnimation();
              bt_Simular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/IconePlaySimular.png")));
              bt_Simular.setActionCommand("Simular");
        }
     
}//GEN-LAST:event_bt_SimularActionPerformed

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

        EspacoDeBusca espacoDeBusca = EspacoDeBusca.getInstance();
        
        if(jComboBox1.getSelectedIndex()==0){
            System.out.println("A0");
            espacoDeBusca.estabelecerObjetivoDaExecucao(EspacoDeBusca.ESTABILIZAR_SWARM);
        }
        if(jComboBox1.getSelectedIndex()==1){
             System.out.println("B0");
            espacoDeBusca.estabelecerObjetivoDaExecucao(EspacoDeBusca.ALCANACAR_ALVO);
        }
        if(jComboBox1.getSelectedIndex()==2){
             System.out.println("C0");
            espacoDeBusca.estabelecerObjetivoDaExecucao(EspacoDeBusca.EXPLORAR_AMBIENTE);
            
            //Setar o sensor fitness dos agentes como sensor fotográfico
            ConjuntoDeAgentes agentes = espacoDeBusca.getAgentes();
            if( !(agentes.get(0).getSensorFitness() instanceof SensorFotografico) ){
                for(int index=0; index < agentes.getNumAgentes(); index++){
                    SensorFotografico sensor = new SensorFotografico(agentes.get(index).getMemoriaDeSolucoes(),index,null);
                    agentes.get(index).setSensorFitness(sensor);
                }
            }
        }
        if(jComboBox1.getSelectedIndex()==3){
             System.out.println("D0");
            espacoDeBusca.estabelecerObjetivoDaExecucao(EspacoDeBusca.EXECUTAR_PSO);

            //Setar o sensor fitness dos agentes como sensor químico
            ConjuntoDeAgentes agentes = espacoDeBusca.getAgentes();
            if( !(agentes.get(0).getSensorFitness() instanceof SensorQuimico) ){
                for(int index=0; index < agentes.getNumAgentes(); index++){
                    SensorQuimico sensor = new SensorQuimico();
                    agentes.get(index).setSensorFitness(sensor);
                }
            }
        }
}//GEN-LAST:event_jComboBox1ActionPerformed

private void bt_VerMapaResultadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_VerMapaResultadoActionPerformed
        BufferedImage mapaFinal = new BufferedImage(canvas.getImagemAmbiente().getWidth(), canvas.getImagemAmbiente().getHeight(), BufferedImage.TYPE_INT_RGB);
        int heightMapaFinal = mapaFinal.getHeight();
        int widthMapaFinal = mapaFinal.getWidth();
        int indice;
        EspacoDeBusca espacoDeBusca = EspacoDeBusca.getInstance();
        ConjuntoDeAgentes conjuntoDeAgentes = espacoDeBusca.getAgentes();
        Agente agente;
        BufferedImage fotoDoAgente;

        int[] pontos_mapaFinal = new int[widthMapaFinal * heightMapaFinal];
        mapaFinal.getRGB(0, 0, widthMapaFinal, heightMapaFinal, pontos_mapaFinal, 0, widthMapaFinal);
        int[] pontos_mapaAgente = new int[widthMapaFinal * heightMapaFinal];
        System.out.println("Construção de mapa de todos os agentes...");
        for(int i = 0;i<conjuntoDeAgentes.getNumAgentes();i++){
            agente = conjuntoDeAgentes.get(i);
            fotoDoAgente = ((SensorFotografico)agente.getSensorFitness()).construirMapa();
            fotoDoAgente.getRGB(0, 0, widthMapaFinal, heightMapaFinal, pontos_mapaAgente, 0, widthMapaFinal);
            for (int linha = 0; linha < heightMapaFinal; linha++) {
                for (int coluna = 0; coluna < widthMapaFinal; coluna++) {
                   indice = linha * widthMapaFinal + coluna;
                   pontos_mapaFinal[indice] = pontos_mapaFinal[indice] | pontos_mapaAgente[indice];
                }
            }

        }  
        mapaFinal.setRGB(0, 0, widthMapaFinal, heightMapaFinal, pontos_mapaFinal, 0, widthMapaFinal);
        JOptionPane.showMessageDialog(this.getParent().getParent(), new javax.swing.ImageIcon(mapaFinal),null,JOptionPane.PLAIN_MESSAGE,null);
        try{
            ImageIO.write( mapaFinal, "jpg", new File("images\\Sensor Fotografico\\mapaFinal.jpg"));
        } catch (IOException ex) {
                    Logger.getLogger(SensorFotografico.class.getName()).log(Level.SEVERE, null, ex);
        }
         System.out.println("Fim da construção de mapa de todos os agentes...");
        
         BufferedImage mapaOtimo =  espacoDeBusca.getMelhorSolucaoPossivel().getFotoRegiao();

         double porcentagemDePixelsIguais = espacoDeBusca.compararImagens(mapaFinal, mapaOtimo);
         System.out.println("Porcentagem Pixels Iguais: "+ porcentagemDePixelsIguais);
}//GEN-LAST:event_bt_VerMapaResultadoActionPerformed

private void tf_NumMaxCiclosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_NumMaxCiclosActionPerformed
    EspacoDeBusca espacoDeBusca = EspacoDeBusca.getInstance();
    int numMaxCiclos = Integer.parseInt(tf_NumMaxCiclos.getText());
    espacoDeBusca.setNumMaxCiclos(numMaxCiclos);
}//GEN-LAST:event_tf_NumMaxCiclosActionPerformed

private void tf_IntervaloVerificacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_IntervaloVerificacaoActionPerformed
    EspacoDeBusca espacoDeBusca = EspacoDeBusca.getInstance();
    int intervalo = Integer.parseInt(tf_IntervaloVerificacao.getText());
    espacoDeBusca.setCicloGatilho(intervalo);
}//GEN-LAST:event_tf_IntervaloVerificacaoActionPerformed

private void tf_PorcentagemMinCompletaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_PorcentagemMinCompletaActionPerformed
    EspacoDeBusca espacoDeBusca = EspacoDeBusca.getInstance();
    int porcentagem = Integer.parseInt(tf_PorcentagemMinCompleta.getText());
    espacoDeBusca.setPorcentagemMinimaCompleta(porcentagem);
}//GEN-LAST:event_tf_PorcentagemMinCompletaActionPerformed

     public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame =  new JFrame();
                PainelFerramentaSimulacao panel = new PainelFerramentaSimulacao(null);
                panel.setPreferredSize(new java.awt.Dimension(200,300));
                panel.setVisible(true);
                frame.setContentPane(panel);
                frame.setVisible(true);
                frame.setSize(new java.awt.Dimension(200,300));
                frame.pack();
            }
        });
    }
     
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_AnimacaoConfig;
    private javax.swing.JButton bt_Simular;
    private javax.swing.JButton bt_VerMapaResultado;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField tf_IntervaloVerificacao;
    private javax.swing.JTextField tf_NumMaxCiclos;
    private javax.swing.JTextField tf_PorcentagemMinCompleta;
    // End of variables declaration//GEN-END:variables

}
