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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author awolf
 */
public class Menu extends javax.swing.JFrame {

    private final String NOME_DRIVER = "org.postgresql.Driver";
    private final String LOCAL_BANCO_DADOS = "jdbc:postgresql://localhost:5432/teste";
    private final String USUARIO = "postgres";
    private final String SENHA = "postgres";

    private Connection conexao = null;
    private Statement st1 = null;
    private ResultSet rs1 = null;

    public Menu() {
        initComponents();

        try {
            Class.forName(NOME_DRIVER).newInstance();
            conexao = DriverManager.getConnection(LOCAL_BANCO_DADOS, USUARIO, SENHA);
            st1 = conexao.createStatement(DEFAULT_CURSOR, DISPOSE_ON_CLOSE);            
            rs1 = st1.executeQuery("SELECT * FROM cliente");            
        } catch (Exception e) {
            Mensagens.erro("Erro ao conectar o banco de dados");
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        spInfo = new javax.swing.JScrollPane();
        tbinfo = new javax.swing.JTable();
        btCarregar = new javax.swing.JButton();
        btFechar = new javax.swing.JButton();
        tfCodigo = new javax.swing.JTextField();
        tfNome = new javax.swing.JTextField();
        btPrimeiro = new javax.swing.JButton();
        btAvanca = new javax.swing.JButton();
        btRetrocede = new javax.swing.JButton();
        btUltimo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tbinfo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        spInfo.setViewportView(tbinfo);

        btCarregar.setText("Carregar");
        btCarregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCarregarActionPerformed(evt);
            }
        });

        btFechar.setText("Fechar");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });

        tfCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfCodigoActionPerformed(evt);
            }
        });

        btPrimeiro.setText("Primeiro");
        btPrimeiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPrimeiroActionPerformed(evt);
            }
        });

        btAvanca.setText("Avança");
        btAvanca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAvancaActionPerformed(evt);
            }
        });

        btRetrocede.setText("Retrocede");
        btRetrocede.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRetrocedeActionPerformed(evt);
            }
        });

        btUltimo.setText("Ultimo");
        btUltimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btUltimoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(spInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btFechar))
            .addGroup(layout.createSequentialGroup()
                .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfNome))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btCarregar)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btPrimeiro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAvanca)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btRetrocede)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btUltimo)))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(spInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btCarregar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btPrimeiro)
                    .addComponent(btAvanca)
                    .addComponent(btRetrocede)
                    .addComponent(btUltimo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(btFechar))
        );

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

    private void btCarregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCarregarActionPerformed
        try {
            Statement st = conexao.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM cliente");

            /* 
               @author: Alexnadre Wolf
               @date: 31/07/2019
               @utility: O codigo abaixo é utilizado para carregar os dados para a tabela
               Foi utilizado o vector para criar uma lista encadeada para
             */
            Vector cabecalho = new Vector();
            cabecalho.add("Codigo");
            cabecalho.add("Nome");

            Vector linhas = new Vector();
            while (rs.next()) {
                Vector colunas = new Vector();
                colunas.add(rs.getString("codigo"));
                colunas.add(rs.getString("nome"));
                linhas.add(new Vector(colunas));
            }

            tbinfo.setModel(new DefaultTableModel(linhas, cabecalho));

        } catch (Exception e) {
            Mensagens.erro("Erro ao carregar dados para a tabela");
            e.printStackTrace();
        }
    }//GEN-LAST:event_btCarregarActionPerformed

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

    private void btPrimeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPrimeiroActionPerformed
        try {
            if (rs1.first()) {
                tfCodigo.setText(rs1.getString("codigo"));
                tfNome.setText(rs1.getString("nome"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btPrimeiroActionPerformed

    private void btAvancaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAvancaActionPerformed
        try {
            if (rs1.next()) {
                tfCodigo.setText(rs1.getString("codigo"));
                tfNome.setText(rs1.getString("nome"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btAvancaActionPerformed

    private void btRetrocedeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRetrocedeActionPerformed
        try {
            if (rs1.previous()) {
                tfCodigo.setText(rs1.getString("codigo"));
                tfNome.setText(rs1.getString("nome"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btRetrocedeActionPerformed

    private void btUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btUltimoActionPerformed
        try {
            if (rs1.last()) {
                tfCodigo.setText(rs1.getString("codigo"));
                tfNome.setText(rs1.getString("nome"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btUltimoActionPerformed

    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFecharActionPerformed
        dispose();
    }//GEN-LAST:event_btFecharActionPerformed

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

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAvanca;
    private javax.swing.JButton btCarregar;
    private javax.swing.JButton btFechar;
    private javax.swing.JButton btPrimeiro;
    private javax.swing.JButton btRetrocede;
    private javax.swing.JButton btUltimo;
    private javax.swing.JScrollPane spInfo;
    private javax.swing.JTable tbinfo;
    private javax.swing.JTextField tfCodigo;
    private javax.swing.JTextField tfNome;
    // End of variables declaration//GEN-END:variables
}
