/*
 * 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 screen.craof.insumo;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.table.DefaultTableModel;
import org.controle.craof.Controle_CRUD_Insumo;

import org.entidade.craof.Insumo;
import org.entidade.craof.Plantio;
import screen.craof.FrameAuxiliar;
import screen.craof.SegundaTela;
import screen.craof.aplicacaoInsumos.AplicacaoInsumo;
import screen.craof.cultura.PanelCulturaBuscar;
import screen.craof.cultura.PanelCulturaCadastrar;
import screen.craof.fichas.CompraInsumos.CompraInsumosCadastrar;
import screen.craof.produzirInsumo.ProduzirInsumo;

/**
 *
 * @author Luan
 */
public class PanelInsumoBuscar extends javax.swing.JPanel {

    /**
     * Creates new form PanelInsumoBuscar
     */
    public PanelInsumoBuscar(JFrame frame) {
        initComponents();
        this.frame = frame;
        inicializar();
    }

    public void inicializar() {
        insumo = new Insumo();
        controle = new Controle_CRUD_Insumo();
        listaInsumo = new ArrayList();
        alterar.setVisible(true);
        insumo.setDescricao(wtDescricao.getText().toUpperCase());
        insumo.setId_usuario(1);
        if (frame instanceof FrameAuxiliar) {
            FrameAuxiliar c = (FrameAuxiliar) frame;
            //Busca os que não foram produzidos no local
            if (c.getPanel() instanceof CompraInsumosCadastrar) {
                alterar.setVisible(false);
                insumo.setFlagProducao(false);
            } else if (c.getPanel() instanceof PanelInsumoCadastrar) {
                alterar.setVisible(false);
                insumo.setFlagProducao(false);
            } else {
                insumo.setFlagProducao(true);
            }
        } else {//Busca todos insumos do usuário não alterado
            insumo.setFlagProducao(null);
        }
        try {
            listaInsumo = controle.buscarTodos(insumo);
            System.out.println(listaInsumo.size());
            DefaultTableModel model = (DefaultTableModel) wtbinsumos.getModel();
            model.getDataVector().removeAllElements();
            for (Insumo aux : listaInsumo) {
                model.addRow(new Object[]{aux.getId_insumo(), aux.getDescricao()});
            }
        } catch (SQLException ex) {
            Logger.getLogger(PanelInsumoBuscar.class.getName()).log(Level.SEVERE, null, ex);
        }

        wsingredientes.setVisible(false);
        wl.setVisible(false);
        wtbingredientes.setVisible(false);
        wlProduzido.setVisible(false);
        jcSim.setVisible(false);
        cancelar.setVisible(false);
        alterar.setVisible(false);

    }

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

        wlDescricao = new javax.swing.JLabel();
        wtDescricao = new javax.swing.JTextField();
        wlProduzido = new javax.swing.JLabel();
        jcSim = new javax.swing.JCheckBox();
        wl = new javax.swing.JLabel();
        buscar1 = new javax.swing.JButton();
        wsingredientes = new javax.swing.JScrollPane();
        wtbingredientes = new javax.swing.JTable();
        cancelar = new javax.swing.JButton();
        wsinsumos = new javax.swing.JScrollPane();
        wtbinsumos = new javax.swing.JTable();
        selecionar = new javax.swing.JButton();
        cancelar1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        alterar = new javax.swing.JButton();

        wlDescricao.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        wlDescricao.setText("Descrição do Insumo:");

        wtDescricao.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        wtDescricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                wtDescricaoActionPerformed(evt);
            }
        });

        wlProduzido.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        wlProduzido.setText("Produzido no Local:");

        jcSim.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jcSim.setText("Sim");
        jcSim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcSimActionPerformed(evt);
            }
        });

        wl.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        wl.setText("Ingredientes");

        buscar1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        buscar1.setText("BUSCAR");
        buscar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscar1ActionPerformed(evt);
            }
        });

        wtbingredientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código do Insumo", "Descrição do Insumo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        wsingredientes.setViewportView(wtbingredientes);

        cancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cancelar.setText("CANCELAR");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        wtbinsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código do Insumo", "Descrição do Insumo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        wsinsumos.setViewportView(wtbinsumos);

        selecionar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        selecionar.setText("SELECIONAR");
        selecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selecionarActionPerformed(evt);
            }
        });

        cancelar1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cancelar1.setText("CANCELAR");
        cancelar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelar1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("BUSCAR INSUMO");

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/craof80.png"))); // NOI18N

        alterar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        alterar.setText("ALTERAR");
        alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(159, 159, 159)
                        .addComponent(alterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(selecionar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelar1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(wsingredientes)
                    .addComponent(wsinsumos, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(196, 196, 196)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(282, 282, 282)
                        .addComponent(cancelar)))
                .addGap(0, 278, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(wlDescricao)
                    .addComponent(wlProduzido))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(wl)
                    .addComponent(jcSim)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(wtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buscar1)))
                .addGap(130, 130, 130))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buscar1)
                    .addComponent(wtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(wlDescricao))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcSim)
                    .addComponent(wlProduzido))
                .addGap(18, 18, 18)
                .addComponent(wl)
                .addGap(18, 18, 18)
                .addComponent(wsingredientes, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelar)
                .addGap(21, 21, 21)
                .addComponent(wsinsumos, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selecionar)
                    .addComponent(cancelar1)
                    .addComponent(alterar))
                .addContainerGap(48, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jcSimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcSimActionPerformed
        System.out.println("bbb");
        if (jcSim.isSelected()) {
//            System.out.println("bbb");
            System.out.println(frame.getClass().toString());
            wsingredientes.setVisible(true);
            wl.setVisible(true);
            wtbingredientes.setVisible(true);
        } else {
            System.out.println("aaaa: " + frame.getClass().toString());
            wsingredientes.setVisible(false);
            wl.setVisible(false);
            wtbingredientes.setVisible(false);
            ((SegundaTela) frame).setTela(this);
        }
        if (frame instanceof SegundaTela) {
            ((SegundaTela) frame).corrigir();
        } else {
            ((FrameAuxiliar) frame).corrigir();
        }
    }//GEN-LAST:event_jcSimActionPerformed

    private void selecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selecionarActionPerformed
        int linha = wtbinsumos.getSelectedRow();
        if (linha >= 0) {
            if (frame instanceof SegundaTela) {
                try {
                    montar((Integer) wtbinsumos.getValueAt(linha, 0));
                } catch (SQLException ex) {
                    Logger.getLogger(PanelInsumoBuscar.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                FrameAuxiliar c = (FrameAuxiliar) frame;
                Insumo insumo = new Insumo();
                insumo.setId_insumo((Integer) wtbinsumos.getValueAt(linha, 0));
                insumo.setDescricao((String) wtbinsumos.getValueAt(linha, 1));
                System.out.println(c.getPanel().getClass().toString());
                if (c.getPanel() instanceof PanelInsumoBuscar) {
                    ((PanelInsumoBuscar) c.getPanel()).inserirTabela(insumo);
                } else if (c.getPanel() instanceof CompraInsumosCadastrar) {
//                    System.out.println("a: " + insumo.getDescricao());
//                    System.out.println("a: " + insumo.getId_insumo());
                    ((CompraInsumosCadastrar) c.getPanel()).setInsumo(insumo);
                    c.fechar();
                } else if (c.getPanel() instanceof PanelInsumoCadastrar) {

                    ((PanelInsumoCadastrar) c.getPanel()).inserirTabela(insumo);
                    c.fechar();
                } else if (c.getPanel() instanceof AplicacaoInsumo) {
                    ((AplicacaoInsumo) c.getPanel()).setInsumo(insumo);
                    c.fechar();
                } else if (c.getPanel() instanceof ProduzirInsumo) {
                    if (retorno == null) {
                        try {
                            montar2(insumo.getId_insumo());
                            retorno = insumo;
                        } catch (SQLException ex) {
                            Logger.getLogger(PanelInsumoBuscar.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        System.out.println(retorno.getId_insumo());
                        ((ProduzirInsumo) c.getPanel()).setInsumo(retorno);
                        c.fechar();
                    }
                }
                //colocar na ficha certa

            }
        } else {
            JOptionPane.showMessageDialog(null, "ERROR CRAOFx03 : Selecione uma linha da tabela.");
        }
    }//GEN-LAST:event_selecionarActionPerformed

    public void inserirTabela(Insumo insumo) {
        //Inserir esse dado na tabela
    }

    public void montar(int id) throws SQLException {
        cancelar.setVisible(true);
        cancelar1.setVisible(false);
        selecionar.setVisible(false);
        wsinsumos.setVisible(false);
        wlProduzido.setVisible(true);
        jcSim.setVisible(true);
        buscar1.setVisible(false);
        jcSim.setEnabled(false);
        //buscar Insumo com este id;
        Insumo s = controle.buscarById(id);
        wtDescricao.setText(s.getDescricao());
        wtDescricao.setEnabled(false);
        if (s.getFlagProducao()) {
            wsingredientes.setVisible(true);
            wl.setVisible(true);
//            jcSim.setVisible(true);
//            jcSim.setSelected(true);
            wtbingredientes.setVisible(true);
            s.getListaInsumo().addAll(controle.buscarTodosItens(s));
            DefaultTableModel model = (DefaultTableModel) wtbingredientes.getModel();
            model.getDataVector().removeAllElements();
            for (Insumo aux : s.getListaInsumo()) {
                model.addRow(new Object[]{aux.getId_insumo(), aux.getDescricao()});
            }
            ((SegundaTela) frame).corrigir();
            //buscar todos os itensProdutos para este id
        }
    }

    public void montar2(int id) throws SQLException {

        //cancelar1.setVisible(false);
        wsinsumos.setVisible(false);
        wlProduzido.setVisible(true);
        jcSim.setVisible(true);
        buscar1.setVisible(false);
        jcSim.setEnabled(false);
        cancelar.setVisible(false);

        //buscar Insumo com este id;
        Insumo s = controle.buscarById(id);
        wtDescricao.setText(s.getDescricao());
        wtDescricao.setEnabled(false);
        wsingredientes.setVisible(true);
        wl.setVisible(true);
        jcSim.setVisible(true);
        jcSim.setSelected(true);
        wtbingredientes.setVisible(true);
        s.getListaInsumo().addAll(controle.buscarTodosItens(s));
        DefaultTableModel model = (DefaultTableModel) wtbingredientes.getModel();
        model.getDataVector().removeAllElements();
        for (Insumo aux : s.getListaInsumo()) {
            model.addRow(new Object[]{aux.getId_insumo(), aux.getDescricao()});
        }
        if (frame instanceof SegundaTela) {
            ((SegundaTela) frame).corrigir();
        }
        //buscar todos os itensProdutos para este id

    }
    private void buscarItemInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarItemInsumoActionPerformed
        FrameAuxiliar c = new FrameAuxiliar(this);
        c.abrirPanel(new PanelCulturaBuscar(frame), "CRAOF");
        c.setVisible(true);
    }//GEN-LAST:event_buscarItemInsumoActionPerformed


    private void cancelar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelar1ActionPerformed
        if (frame instanceof FrameAuxiliar) {
            ((FrameAuxiliar) frame).fechar();
        } else {
            ((SegundaTela) frame).voltar();
        }
    }//GEN-LAST:event_cancelar1ActionPerformed

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

    private void buscar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscar1ActionPerformed
        insumo = new Insumo();
        controle = new Controle_CRUD_Insumo();
        listaInsumo = new ArrayList();
        alterar.setVisible(true);
        //System.out.println(wtDescricao.getText());
        insumo.setDescricao(wtDescricao.getText().toUpperCase());
        insumo.setId_usuario(1);
        if (frame instanceof FrameAuxiliar) {
            FrameAuxiliar c = (FrameAuxiliar) frame;
            //Busca os que não foram produzidos no local
            if (c.getPanel() instanceof CompraInsumosCadastrar) {
                alterar.setVisible(false);
                insumo.setFlagProducao(false);
            } else if (c.getPanel() instanceof PanelInsumoCadastrar) {
                alterar.setVisible(false);
                insumo.setFlagProducao(false);
            } else {
                insumo.setFlagProducao(true);
            }
        } else {//Busca todos insumos do usuário não alterado
            insumo.setFlagProducao(null);
        }
        try {
            listaInsumo = controle.buscarTodos(insumo);
            System.out.println(listaInsumo.size());
            if (listaInsumo.size() == 0) {
                System.out.println("aa");
                Object[] options = {"Sim", "Não"};
                int n = JOptionPane.showOptionDialog(frame, "Deseja cadastrar essa cultura?", "Confirmação de cadastro",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
                if (n == 0) {
                    FrameAuxiliar c = new FrameAuxiliar(this);
                    c.abrirPanel(new PanelInsumoCadastrar(c), "CRAOF");
                    c.setVisible(true);
                }
            } else {
                DefaultTableModel model = (DefaultTableModel) wtbinsumos.getModel();
                model.getDataVector().removeAllElements();
                for (Insumo aux : listaInsumo) {
                    model.addRow(new Object[]{aux.getId_insumo(), aux.getDescricao()});
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(PanelInsumoBuscar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_buscar1ActionPerformed

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        if (frame instanceof FrameAuxiliar) {
            ((FrameAuxiliar) frame).fechar();
        } else {
            ((SegundaTela) frame).voltar();
        }
    }//GEN-LAST:event_cancelarActionPerformed

    private void alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterarActionPerformed
        insumo = new Insumo();
        insumo.setId_insumo(listaInsumo.get(wtbinsumos.getSelectedRow()).getId_insumo());
        insumo.setDescricao(listaInsumo.get(wtbinsumos.getSelectedRow()).getDescricao());
        insumo.setAlterado(Boolean.TRUE);
        FrameAuxiliar c = new FrameAuxiliar(this);
        try {
            c.abrirPanel(new PanelInsumoCadastrar(c), "Alterar insumo - CRAOF");
            c.setVisible(true);
            ((PanelInsumoCadastrar) c.getPanelGo()).setInsumo(insumo);
        } catch (SQLException ex) {
            Logger.getLogger(PanelInsumoBuscar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_alterarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton alterar;
    private javax.swing.JButton buscar1;
    private javax.swing.JButton cancelar;
    private javax.swing.JButton cancelar1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JCheckBox jcSim;
    private javax.swing.JButton selecionar;
    private javax.swing.JLabel wl;
    private javax.swing.JLabel wlDescricao;
    private javax.swing.JLabel wlProduzido;
    private javax.swing.JScrollPane wsingredientes;
    private javax.swing.JScrollPane wsinsumos;
    private javax.swing.JTextField wtDescricao;
    private javax.swing.JTable wtbingredientes;
    private javax.swing.JTable wtbinsumos;
    // End of variables declaration//GEN-END:variables
    private JFrame frame;
    private Insumo insumo;
    private Controle_CRUD_Insumo controle;
    private ArrayList<Insumo> listaInsumo;
    private Insumo retorno;
}
