/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
 */
package guimybank;

import java.awt.Color;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

/**
 *
 * @author Verde
 */
public class GUIMyBank extends javax.swing.JFrame {

    static Border borderOriginale = UIManager.getBorder("TextField.border");
    static ContoCorrente contoCorrente;

    private static final java.util.logging.Logger logger = java.util.logging.Logger
            .getLogger(GUIMyBank.class.getName());

    /**
     * Creates new form GUIMyBank
     */
    public GUIMyBank() {
        initComponents();
        btnVersamento.setVisible(false);
        btnPrelievo.setVisible(false);
        btnListaMovimenti.setVisible(false);
        txtaListaMovimenti.setVisible(false);
        txtaListaMovimenti.setEditable(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
    // <editor-fold defaultstate="collapsed" desc="Generated
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblNome = new javax.swing.JLabel();
        lblCognome = new javax.swing.JLabel();
        lblCodiceFiscale = new javax.swing.JLabel();
        lblDataDiNascita = new javax.swing.JLabel();
        lblSaldoIniziale = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        txtCognome = new javax.swing.JTextField();
        txtCodiceFiscale = new javax.swing.JTextField();
        txtDataDiNascita = new javax.swing.JTextField();
        txtSaldoIniziale = new javax.swing.JTextField();
        btnDataDiNascita = new javax.swing.JButton();
        btnAprireContoCorrente = new javax.swing.JButton();
        btnVersamento = new javax.swing.JButton();
        btnPrelievo = new javax.swing.JButton();
        btnListaMovimenti = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtaListaMovimenti = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblNome.setText("Nome");

        lblCognome.setText("Cognome");

        lblCodiceFiscale.setText("Codice fiscale");

        lblDataDiNascita.setText("Data di nascita");

        lblSaldoIniziale.setText("Saldo iniziale");

        txtNome.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtNomeFocusGained(evt);
            }
        });

        txtCognome.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCognomeFocusGained(evt);
            }
        });

        txtCodiceFiscale.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCodiceFiscaleFocusGained(evt);
            }
        });

        txtDataDiNascita.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtDataDiNascitaFocusGained(evt);
            }
        });

        txtSaldoIniziale.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtSaldoInizialeFocusGained(evt);
            }
        });

        btnDataDiNascita.setText("[]");

        btnAprireContoCorrente.setText("Aprire conto corrente");
        btnAprireContoCorrente.addActionListener(this::btnAprireContoCorrenteActionPerformed);

        btnVersamento.setText("Versamento");
        btnVersamento.addActionListener(this::btnVersamentoActionPerformed);

        btnPrelievo.setText("Prelievo");
        btnPrelievo.addActionListener(this::btnPrelievoActionPerformed);

        btnListaMovimenti.setText("Lista movimenti");
        btnListaMovimenti.addActionListener(this::btnListaMovimentiActionPerformed);

        txtaListaMovimenti.setColumns(20);
        txtaListaMovimenti.setRows(5);
        jScrollPane1.setViewportView(txtaListaMovimenti);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblDataDiNascita)
                                    .addComponent(lblSaldoIniziale))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtDataDiNascita, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(btnDataDiNascita, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(txtSaldoIniziale))
                                .addGap(37, 37, 37)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnVersamento)
                                    .addComponent(btnPrelievo)
                                    .addComponent(btnListaMovimenti)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblNome)
                                    .addComponent(lblCognome)
                                    .addComponent(lblCodiceFiscale))
                                .addGap(26, 26, 26)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtCodiceFiscale, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtCognome, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(99, 99, 99)
                        .addComponent(btnAprireContoCorrente))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNome)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCognome)
                    .addComponent(txtCognome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnVersamento))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCodiceFiscale)
                    .addComponent(txtCodiceFiscale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPrelievo))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDataDiNascita)
                    .addComponent(txtDataDiNascita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDataDiNascita)
                    .addComponent(btnListaMovimenti))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSaldoIniziale)
                    .addComponent(txtSaldoIniziale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnAprireContoCorrente)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(9, Short.MAX_VALUE))
        );

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

    private void btnListaMovimentiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListaMovimentiActionPerformed
        txtaListaMovimenti.setText(contoCorrente.getLogOperazioni());
        txtaListaMovimenti.setVisible(true);
    }//GEN-LAST:event_btnListaMovimentiActionPerformed

    private void txtNomeFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtNomeFocusGained
        txtNome.setBorder(borderOriginale);
    }// GEN-LAST:event_txtNomeFocusGained

    private void txtCognomeFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtCognomeFocusGained
        txtCognome.setBorder(borderOriginale);
    }// GEN-LAST:event_txtCognomeFocusGained

    private void txtCodiceFiscaleFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtCodiceFiscaleFocusGained
        txtCodiceFiscale.setBorder(borderOriginale);
    }// GEN-LAST:event_txtCodiceFiscaleFocusGained

    private void txtDataDiNascitaFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtDataDiNascitaFocusGained
        txtDataDiNascita.setBorder(borderOriginale);
    }// GEN-LAST:event_txtDataDiNascitaFocusGained

    private void txtSaldoInizialeFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtSaldoInizialeFocusGained
        txtSaldoIniziale.setBorder(borderOriginale);
    }// GEN-LAST:event_txtSaldoInizialeFocusGained

    private void btnVersamentoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnVersamentoActionPerformed
        String versamento;
        boolean error;

        do {
            error = false;
            versamento = JOptionPane.showInputDialog("Inserire l'importo da versare:");
            if (!isNumeroValid(versamento)) {
                JOptionPane.showMessageDialog(null, "L'importo che si desidera versare non è valido.");
                error = true;
            } else {
                contoCorrente.versa(Double.parseDouble(versamento));
                lblSaldoIniziale.setText("Saldo");
                txtSaldoIniziale.setText(Double.toString(contoCorrente.getSaldo()));
            }
        } while (error);
    }// GEN-LAST:event_btnVersamentoActionPerformed

    private void btnPrelievoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnPrelievoActionPerformed
        String prelievo;
        boolean error;

        do {
            error = false;
            prelievo = JOptionPane.showInputDialog("Inserire l'importo da prelevare:");
            if (!isNumeroValid(prelievo)) {
                JOptionPane.showMessageDialog(null, "L'importo che si desidera prelevare non è valido.");
                error = true;
            } else {
                try {
                    contoCorrente.preleva(Double.parseDouble(prelievo));
                    lblSaldoIniziale.setText("Saldo");
                    txtSaldoIniziale.setText(Double.toString(contoCorrente.getSaldo()));
                } catch (IllegalArgumentException e) {
                    JOptionPane.showMessageDialog(null, e.getMessage());
                    error = true;
                }
            }
        } while (error);
    }// GEN-LAST:event_btnPrelievoActionPerformed

    private void btnAprireContoCorrenteActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnAprireContoCorrenteActionPerformed
        String nome = txtNome.getText();
        String cognome = txtCognome.getText();
        String codiceFiscale = txtCodiceFiscale.getText();
        // String dataDiNascita = txtDataDiNascita.getText();
        String saldoIniziale = txtSaldoIniziale.getText();
        boolean nomeEmpty = nome.isEmpty();
        boolean cognomeEmpty = cognome.isEmpty();
        boolean codiceFiscaleEmpty = codiceFiscale.isEmpty();
        // boolean dataDiNascitaEmpty = dataDiNascita.isEmpty();
        boolean saldoInizialeEmpty = saldoIniziale.isEmpty();

        if (nomeEmpty || cognomeEmpty || codiceFiscaleEmpty /* || dataDiNascitaEmpty */ || saldoInizialeEmpty) {
            if (nomeEmpty) {
                txtNome.setBorder(new LineBorder(Color.red));
            }
            if (cognomeEmpty) {
                txtCognome.setBorder(new LineBorder(Color.red));
            }
            if (codiceFiscaleEmpty) {
                txtCodiceFiscale.setBorder(new LineBorder(Color.red));
            }
            /*
             * if(dataDiNascitaEmpty){
             * txtDataDiNascita.setBorder(new LineBorder(Color.red));
             * }
             */
            if (saldoInizialeEmpty) {
                txtSaldoIniziale.setBorder(new LineBorder(Color.red));
            }
            JOptionPane.showMessageDialog(null, "Inserire tutti i dati richiesti.");
            return;
        }

        if (isCodiceFiscaleValid(codiceFiscale)) {
            JOptionPane.showMessageDialog(null, "Il codice fiscale non è valido.");
            txtCodiceFiscale.setBorder(new LineBorder(Color.red));
            return;
        }
        // TODO: gestione data
        // if(dataDiNascita.isEmpty()){
        // dataDiNascitaError = true;
        // }
        if (!isNumeroValid(saldoIniziale)) {
            JOptionPane.showMessageDialog(null, "Il saldo iniziale non è valido.");
            txtSaldoIniziale.setBorder(new LineBorder(Color.red));
            return;
        }

        contoCorrente = new ContoCorrente(nome, cognome, codiceFiscale, Double.parseDouble(saldoIniziale));

        btnVersamento.setVisible(true);
        btnPrelievo.setVisible(true);
        btnListaMovimenti.setVisible(true);
        txtNome.setEditable(false);
        txtCognome.setEditable(false);
        txtCodiceFiscale.setEditable(false);
        txtDataDiNascita.setEditable(false);
        txtSaldoIniziale.setEditable(false);
        btnAprireContoCorrente.setEnabled(false);
        btnDataDiNascita.setEnabled(false);

    }// GEN-LAST:event_btnAprireContoCorrenteActionPerformed

    boolean isCodiceFiscaleValid(String codiceFiscale) {
        Pattern pattern = Pattern.compile("[A-Z]{6}[ABCDEHLMPRST]{3}\\d{2}[A-Z]\\d{3}[A-Z]");

        return !pattern.matcher(codiceFiscale).find();
    }

    boolean isNumeroValid(String numero) {
        boolean isNumeroValid = true;
        double valoreNumero;

        try {
            valoreNumero = Double.parseDouble(numero);

            if (valoreNumero <= 0) {
                isNumeroValid = false;
            }
        } catch (NumberFormatException _) {
            isNumeroValid = false;
        }

        return isNumeroValid;
    }

    /**
     * @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 (ReflectiveOperationException | javax.swing.UnsupportedLookAndFeelException ex) {
            logger.log(java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> new GUIMyBank().setVisible(true));
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAprireContoCorrente;
    private javax.swing.JButton btnDataDiNascita;
    private javax.swing.JButton btnListaMovimenti;
    private javax.swing.JButton btnPrelievo;
    private javax.swing.JButton btnVersamento;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCodiceFiscale;
    private javax.swing.JLabel lblCognome;
    private javax.swing.JLabel lblDataDiNascita;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblSaldoIniziale;
    private javax.swing.JTextField txtCodiceFiscale;
    private javax.swing.JTextField txtCognome;
    private javax.swing.JTextField txtDataDiNascita;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtSaldoIniziale;
    private javax.swing.JTextArea txtaListaMovimenti;
    // End of variables declaration//GEN-END:variables
}
