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

import java.awt.Color;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import logic.MyBank;
import logic.ContoCorrente;
import logic.ContoCorrenteWrapper;

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 contoCorrenteAperto;

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

    /**
     * Creates new form GUIMyBank
     */
    public GUIMyBank() {
        initComponents();
        try {
            ArrayList<ContoCorrente> conti = (ArrayList<ContoCorrente>) MyBank.importaConti();
            MyBank.setConti(conti);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        lblNumeroContoCorrente.setVisible(false);
        txtNumeroContoCorrente.setVisible(false);
        txtNumeroContoCorrente.setEditable(false);
        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
    // <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();
        lblNumeroContoCorrente = new javax.swing.JLabel();
        txtNumeroContoCorrente = new javax.swing.JTextField();

        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);

        lblNumeroContoCorrente.setText("Numero conto corrente:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(99, 99, 99)
                                .addComponent(btnAprireContoCorrente)
                                .addContainerGap(187, Short.MAX_VALUE))
                        .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)))
                                        .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))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39,
                                        Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(lblNumeroContoCorrente, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(btnVersamento)
                                        .addComponent(btnPrelievo)
                                        .addComponent(btnListaMovimenti)
                                        .addComponent(txtNumeroContoCorrente))
                                .addGap(23, 23, 23))
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1)
                                .addContainerGap()));
        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)
                                        .addComponent(lblNumeroContoCorrente))
                                .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(txtNumeroContoCorrente, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .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))
                                                .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))
                                                .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)))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(btnVersamento)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnPrelievo)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnListaMovimenti)))
                                .addGap(18, 18, 18)
                                .addComponent(btnAprireContoCorrente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1)
                                .addGap(14, 14, 14)));

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

    private void btnListaMovimentiActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnListaMovimentiActionPerformed
        try {
            txtaListaMovimenti.setText(contoCorrenteAperto.getLog());
            txtaListaMovimenti.setVisible(true);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }// 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
        double versamento;
        boolean error;

        do {
            error = false;
            try {
                versamento = MyBank.valoreDouble(JOptionPane.showInputDialog("Inserire l'importo da versare:"));

                contoCorrenteAperto.versa(versamento);
                lblSaldoIniziale.setText("Saldo");
                txtSaldoIniziale.setText(Double.toString(contoCorrenteAperto.getSaldo()));
            } catch (NumberFormatException _) {
                JOptionPane.showMessageDialog(null, "L'importo che si desidera versare non è valido.");
                error = true;
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
            }
        } while (error);
    }// GEN-LAST:event_btnVersamentoActionPerformed

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

        do {
            error = false;
            try {
                prelievo = MyBank.valoreDouble(JOptionPane.showInputDialog("Inserire l'importo da versare:"));

                contoCorrenteAperto.preleva(prelievo);
                lblSaldoIniziale.setText("Saldo");
                txtSaldoIniziale.setText(Double.toString(contoCorrenteAperto.getSaldo()));
            } catch (NumberFormatException _) {
                JOptionPane.showMessageDialog(null, "L'importo che si desidera prelevare non è valido.");
                error = true;
            } catch (IllegalArgumentException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
                error = true;
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
            }
        } while (error);
    }// GEN-LAST:event_btnPrelievoActionPerformed

    private void btnAprireContoCorrenteActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnAprireContoCorrenteActionPerformed
        String nome = txtNome.getText().trim();
        String cognome = txtCognome.getText().trim();
        String codiceFiscale = txtCodiceFiscale.getText().trim().toUpperCase();
        String dataDiNascitaString = txtDataDiNascita.getText().trim();
        Date dataDiNascita;
        String saldoInizialeString = txtSaldoIniziale.getText().trim();
        double saldoIniziale;
        boolean nomeEmpty = nome.isEmpty();
        boolean cognomeEmpty = cognome.isEmpty();
        boolean codiceFiscaleEmpty = codiceFiscale.isEmpty();
        boolean dataDiNascitaEmpty = dataDiNascitaString.isEmpty();
        boolean saldoInizialeEmpty = saldoInizialeString.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 (MyBank.isCodiceFiscaleValid(codiceFiscale)) {
            JOptionPane.showMessageDialog(null, "Il codice fiscale non è valido.");
            txtCodiceFiscale.setBorder(new LineBorder(Color.red));
            return;
        }

        try {
            dataDiNascita = MyBank.dataDiNascita(dataDiNascitaString);
        } catch (ParseException _) {
            JOptionPane.showMessageDialog(null, "La data di nascita non è valida.");
            txtDataDiNascita.setBorder(new LineBorder(Color.red));
            return;
        }

        try {
            saldoIniziale = MyBank.valoreDouble(saldoInizialeString);
        } catch (NumberFormatException _) {
            JOptionPane.showMessageDialog(null, "Il saldo iniziale non è valido.");
            txtSaldoIniziale.setBorder(new LineBorder(Color.red));
            return;
        }

        try {
            ContoCorrenteWrapper conto = MyBank.aggiungiConto(nome, cognome, codiceFiscale, dataDiNascita,
                    saldoIniziale);
            contoCorrenteAperto = conto.getConto();

            if (conto.isImported()) {
                JOptionPane.showMessageDialog(null, "Esiste già un conto corrente per il codice fiscale specificato.\nVerrà aperto il conto corrente esistente.");
                txtNome.setText(contoCorrenteAperto.getNome());
                txtCognome.setText(contoCorrenteAperto.getCognome());
                txtCodiceFiscale.setText(contoCorrenteAperto.getCodiceFiscale());
                txtDataDiNascita.setText(MyBank.dataDiNascita(contoCorrenteAperto.getDataDiNascita()));
                txtSaldoIniziale.setText(Double.toString(contoCorrenteAperto.getSaldo()));
                txtNumeroContoCorrente.setText(Integer.toString(contoCorrenteAperto.getNumeroContoCorrente()));
                lblSaldoIniziale.setText("Saldo");

            } else {
                txtNumeroContoCorrente.setText(Integer.toString(MyBank.getConti().getLast().getNumeroContoCorrente()));
            }

            lblNumeroContoCorrente.setVisible(true);
            txtNumeroContoCorrente.setVisible(true);
            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);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

    }// GEN-LAST:event_btnAprireContoCorrenteActionPerformed

    /**
     * @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 lblNumeroContoCorrente;
    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 txtNumeroContoCorrente;
    private javax.swing.JTextField txtSaldoIniziale;
    private javax.swing.JTextArea txtaListaMovimenti;
    // End of variables declaration//GEN-END:variables
}
