package pesquisa;

import java.awt.*;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.JInternalFrame;
import java.util.Vector;
import java.io.File;

/**
 *
 * @author  Eduardo Bezerra
 */
public class SearchForm extends JFrame {

    private Object objetoSelecionado = null;
    
    private Hashtable<String, String> filteringFields;
    private Hashtable<String, String> presentationFields;
    
    private String[] headerFieldNames;
    
    private String selectedFilteringFieldName;
    
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JComboBox cboCampoPesquisa;
    private javax.swing.JPanel pnlSearchDefinition;
    
    private javax.swing.JLabel lblValor;
    private javax.swing.JLabel lblcampo;
    private javax.swing.JTextField txtValor;
    
    private IPesquisaObjetos pesquisadorObjetos;
    
    private ObjectsPresentation searchResult;
    
    public SearchForm(String title,
            IPesquisaObjetos pesquisadorObjetos,
            Hashtable camposPesquisa,
            Hashtable presentationFields) {
        super(title);
        
        this.pesquisadorObjetos = pesquisadorObjetos;
        
        filteringFields = camposPesquisa;
        
        this.presentationFields = presentationFields;
        
        searchResult = new ObjectsPresentation(presentationFields);
        
        // Add the scroll pane to this panel.
        getContentPane().add(searchResult.getContainer());
        
        initComponents();
        
        try {
            for(java.util.Enumeration en = filteringFields.keys(); en.hasMoreElements();/* Nothing */) {
                String key = (String) en.nextElement();
                cboCampoPesquisa.addItem(filteringFields.get(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //setClosable( true );
        setSize( new Dimension(440,300) );
        setPreferredSize( new Dimension(440,300) );
        setMinimumSize( new Dimension(440,300) );
    }
    
    private void initComponents() {
        pnlSearchDefinition = new javax.swing.JPanel();
        txtValor = new javax.swing.JTextField();
        cboCampoPesquisa = new javax.swing.JComboBox();
        btnPesquisar = new javax.swing.JButton();
        lblValor = new javax.swing.JLabel();
        lblcampo = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        
        getContentPane().setLayout(null);
        
        pnlSearchDefinition.setLayout(null);
        
        pnlSearchDefinition.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
        pnlSearchDefinition.add(txtValor);
        txtValor.setBounds(140, 30, 230, 20);
        
        cboCampoPesquisa.setEnabled(true);
        cboCampoPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboSearchFieldActionPerformed(evt);
            }
        });
        
        pnlSearchDefinition.add(cboCampoPesquisa);
        cboCampoPesquisa.setBounds(10, 30, 120, 20);
        
        String curDir = System.getProperty("user.dir");
        btnPesquisar.setIcon(new javax.swing.ImageIcon(curDir + File.separator + "figs/select16.GIF"));
        btnPesquisar.setToolTipText("Pressione para iniciar a pesquisa.");
        pnlSearchDefinition.add(btnPesquisar);
        btnPesquisar.setBounds(380, 30, 20, 20);
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        
        lblValor.setText("Valor");
        pnlSearchDefinition.add(lblValor);
        lblValor.setBounds(140, 10, 50, 16);
        
        lblcampo.setText("Campo");
        pnlSearchDefinition.add(lblcampo);
        lblcampo.setBounds(10, 10, 40, 16);
        
        getContentPane().add(pnlSearchDefinition);
        pnlSearchDefinition.setBounds(10, 10, 410, 60);
        
        btnOK.setText("OK");
        getContentPane().add(btnOK);
        btnOK.setBounds(110, 230, 90, 26);
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });
        
        btnCancel.setText("Cancelar");
        getContentPane().add(btnCancel);
        btnCancel.setBounds(220, 230, 90, 26);
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
    }
    
    // Evento Click do botao "Ok"
    protected void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
        objetoSelecionado = searchResult.getSelectedObject();
        if (objetoSelecionado == null)
            JOptionPane.showMessageDialog(null, "Selecione um objeto.");
        else 
            btnCancelActionPerformed(evt);
    }
    
    // Evento Click do botao "Pesquisar"
    protected void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
        if(validateFields()) {
            searchResult.presentObjects(getResults(selectedFilteringFieldName, txtValor.getText()));
        }
    }
    
    // Evento Click do botao "Cancelar"
    protected void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
        setVisible(false);
    }
    
    private void cboSearchFieldActionPerformed(java.awt.event.ActionEvent evt) {
        if (cboCampoPesquisa.getSelectedIndex() == -1) {
            String msgErro = "É necessário selecionar campo de pesquisa!";
            cboCampoPesquisa.requestFocus();
            JOptionPane.showMessageDialog(null, msgErro);
        } else {
            String filteringFieldLabel = (String) cboCampoPesquisa.getSelectedItem();
            System.out.println("Label = " + filteringFieldLabel);
            
            for(java.util.Enumeration en = filteringFields.keys(); en.hasMoreElements();/* Nothing */) {
                String key = (String) en.nextElement();
                String value = (String) filteringFields.get(key);
                if(value.equals(filteringFieldLabel)) {
                    selectedFilteringFieldName = key;
                    break;
                }
            }
            System.out.println("Name = " + selectedFilteringFieldName);
        }
    }
    
    /**
     * Valida os campos do formulário.
     */
    protected boolean validateFields() {
        boolean ok = true;
        String msgErro = "";
        
        if (txtValor.getText().equals("")) {
            ok = false;
            msgErro = "É necessário o valor a pesquisar!";
            txtValor.requestFocus();
        } else if (cboCampoPesquisa.getSelectedIndex() == -1) {
            ok = false;
            msgErro = "É necessário selecionar a campo a pesquisar!";
            cboCampoPesquisa.requestFocus();
        }
        if (!ok)
            JOptionPane.showMessageDialog(null, msgErro);
        return ok;
    }
    
    private Vector getResults(String filteringField, String filteringValue) {
        return pesquisadorObjetos.getQueryResults(filteringField, filteringValue);
    }
    
    public String getSelectedObjectId()	{
        return searchResult.getSelectedObjectId();
    }

    public Object getObjetoSelecionado() {
        return objetoSelecionado;
    }

    public void setObjetoSelecionado(Object objetoSelecionado) {
        this.objetoSelecionado = objetoSelecionado;
    }
}