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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author atlas
 */
public class AdminRegister extends javax.swing.JFrame {

    private boolean isLoged = false;
    private Connection conexion = null; //Objeto de la clase connection
    private ResultSet result = null; //Objeto de la clase resultSet
    private Statement statement = null; //Objeto de la clase Statement
    private PreparedStatement ps = null; //Objeto de la clase Prepared Statement

    String user = "";
    String password = "";
    String field = "";
    private User us;

    public AdminRegister() {
        initComponents();
        this.setLocationRelativeTo(null);

    }

    public AdminRegister(User u) {
        initComponents();
        this.setLocationRelativeTo(null);
        desactivate();
        us = u;

    }

    public void desactivate() {
        btnInsert.setEnabled(false);
        jButton1.setEnabled(false);

        userText.setEnabled(false);
        passField.setEnabled(false);
        fieldText.setEnabled(false);

    }

    public void activate() {
        btnInsert.setEnabled(true);
        jButton1.setEnabled(true);

        userText.setEnabled(true);
        passField.setEnabled(true);
        fieldText.setEnabled(true);

    }

    public void connection(String username, String pass) {
        String url = "jdbc:postgresql://localhost:5432/parkingManagement";
        /*Direccion por default en donde se
        encuentra la base de datos*/
        if (conexion != null) {
            return;
        }

        try {

            conexion = DriverManager.getConnection(url, us.getUsername(), us.getPassword());

            if (conexion != null) //Verificacion para saber si se conecto correctamente
            {
                System.out.println("Conectando a la base de datos\n");
                JOptionPane.showMessageDialog(null, "Conexión exitosa");
            }

        } catch (Exception e) {
            System.out.println("Error de conexion: " + e.getMessage() + "\n");
        }
    }

    public boolean isValidUser() {
        boolean check = false;
        if (userText.getText().length() > 0) {
            if (passField.getText().length() > 0) {
                if (fieldText.getText().length() > 0) {
                    check = true;
                } else {
                    JOptionPane.showMessageDialog(null, "Error en Campo.");
                    fieldText.requestFocusInWindow();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Error en Contraseña.");
                passField.requestFocusInWindow();

            }
        } else {
            JOptionPane.showMessageDialog(null, "Error en Nombre de Usuario.");
            userText.requestFocusInWindow();
        }

        return check;
    }

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

        userText = new javax.swing.JTextField();
        passField = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btnInsert = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        fieldText = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        btnBack = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(userText, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 90, 210, 30));
        getContentPane().add(passField, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 150, 210, 30));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Campo:");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 220, -1, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Nombre de usuario:");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 90, -1, -1));

        btnInsert.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        btnInsert.setText("Registrar");
        btnInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertActionPerformed(evt);
            }
        });
        getContentPane().add(btnInsert, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 430, 130, 60));

        jLabel4.setFont(new java.awt.Font("Verdana", 1, 24)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("REGISTRO DE ADMINISTRADORES:");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, 510, 40));
        getContentPane().add(fieldText, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 210, 210, 30));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Contraseña:");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 160, -1, -1));

        btnBack.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
        btnBack.setText("Regresar");
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });
        getContentPane().add(btnBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(695, 10, 100, 50));

        jButton1.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 430, 130, 60));

        jButton2.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        jButton2.setText("Nuevo");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 430, 130, 60));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/background.jpg"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 500));

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

    private void btnInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertActionPerformed
        // TODO add your handling code here:
        connection(us.getUsername(), us.getPassword());
        try {
            user = userText.getText();
            password = passField.getText();
            field = fieldText.getText();

            statement = conexion.createStatement();

            if (isValidUser()) {
                statement.executeUpdate("INSERT INTO guardias values ('" + user + "','" + password + "','" + field + "');");

            }

        } catch (Exception e) {
            System.out.println("Error de conexion: " + e.getMessage() + "\n");
        }

    }//GEN-LAST:event_btnInsertActionPerformed

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        // TODO add your handling code here:
        Login login;
        login = new Login(us);
        login.show();
        this.dispose();
    }//GEN-LAST:event_btnBackActionPerformed

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

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

    /**
     * @param args the command line arguments
     */
    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(AdminRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminRegister.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminRegister.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 AdminRegister().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBack;
    private javax.swing.JButton btnInsert;
    private javax.swing.JTextField fieldText;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPasswordField passField;
    private javax.swing.JTextField userText;
    // End of variables declaration//GEN-END:variables
}
