/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package generateurmdp;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
//import java.security.*;
//import sun.security.provider.MD5;

/**
 *
 * @author cedrickaiser2
 */
public class Fenetre extends JFrame implements ActionListener {

    static final String ACTION_GENERATION = "Générer";
    static final String ACTION_ENREGISTRER = "Enregistrer";
    static final String ACTION_MDPSAVED = "MDPSAVED >>";
    static final String ACTION_ESTVISIBLE = "";
    private String mdp = "";
    private String chiffre;
    private String minuscule;
    private String majuscule;
    private String special;
    private String chaineCaractere;
    private int longChaineCaractere;
    private int longDefautMDP = 8;
    private int longMiniMDP = 5;
    private int longMaxMDP = 50;
    private JLabel lblChiffre;
    private JLabel lblChiffre2;
    private JLabel lblMessage;
    private JLabel lblMessageBottom;
    private JLabel lblMDP;
    private JLabel lblMinuscule;
    private JLabel lblMajuscule;
    private JLabel lblSpecial;
    private JLabel lblShowMDP;
    private JLabel lblNbCaractere;
    private JCheckBox chbChiffre;
    private JCheckBox chbMinuscule;
    private JCheckBox chbMajuscule;
    private JCheckBox chbSpecial;
    private JCheckBox chbShowMDP;
    private JTextField tfNbCaractere;
    private JButton btGeneration;
    private JButton btEnregistrer;
    private JTextArea tfMDP2;
    private JPasswordField tfMDP;
    private Connection connec;
    private JButton btMDPSaved;
    private String nomUser;
    private JComboBox nbChiffreMini;
    private String transfertMDP;

    Fenetre(String user) {
        super("Générateur de mot de passe");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setVisible(true);
        this.setLayout(null);

        this.setLocation(100, 100);

        this.initComponent();

        if (testConnection()) {
            btEnregistrer.setEnabled(true);
        }

        nomUser = user;

        pack();
        this.setSize(500, 250);
    }

    public void initComponent() {
        lblMessage = new JLabel("Votre mot de passe sera composé de :");
        lblMessage.setBounds(10, 10, 250, 20);

        lblMDP = new JLabel("Mot de passe enregistré pour l'application :");

        lblChiffre = new JLabel("Chiffre");
        lblChiffre.setBounds(10, 30, 150, 20);

        lblChiffre2 = new JLabel("Nombre mini");
        lblChiffre2.setBounds(200, 30, 150, 20);

        nbChiffreMini = new JComboBox();
        nbChiffreMini.setBounds(300, 30, 60, 20);

        lblMinuscule = new JLabel("Minuscule");
        lblMinuscule.setBounds(10, 50, 150, 20);

        lblMajuscule = new JLabel("Majuscule");
        lblMajuscule.setBounds(10, 70, 150, 20);

        lblSpecial = new JLabel("Spécial");
        lblSpecial.setBounds(10, 90, 150, 20);

        chbChiffre = new JCheckBox("", true);
        chbChiffre.setBounds(160, 30, 30, 30);

        chbMinuscule = new JCheckBox("", true);
        chbMinuscule.setBounds(160, 50, 30, 30);

        chbMajuscule = new JCheckBox("", true);
        chbMajuscule.setBounds(160, 70, 30, 30);

        chbSpecial = new JCheckBox("", false);
        chbSpecial.setBounds(160, 90, 30, 30);

        lblNbCaractere = new JLabel("Nombre de caractère :");
        lblNbCaractere.setBounds(10, 110, 150, 20);

        tfNbCaractere = new JTextField(String.valueOf(longDefautMDP));
        tfNbCaractere.setBounds(160, 110, 30, 30);
        tfNbCaractere.addActionListener(this);

        btGeneration = new JButton(ACTION_GENERATION);
        btGeneration.setBounds(10, 150, 100, 20);
        btGeneration.addActionListener(this);

        btEnregistrer = new JButton(ACTION_ENREGISTRER);
        btEnregistrer.setBounds(150, 150, 100, 20);
        btEnregistrer.setEnabled(false);
        btEnregistrer.addActionListener(this);

        btMDPSaved = new JButton(ACTION_MDPSAVED);
        btMDPSaved.setBounds(290, 150, 100, 20);
        btMDPSaved.addActionListener(this);

        tfMDP = new JPasswordField();
        tfMDP.setBounds(10, 175, 450, 30);

        tfMDP2 = new JTextArea();
        tfMDP2.setBounds(10, 180, 450, 20);

        lblShowMDP = new JLabel("MDP Visible");
        lblShowMDP.setBounds(400, 210, 90, 20);

        chbShowMDP = new JCheckBox(ACTION_ESTVISIBLE);
        chbShowMDP.setBounds(370, 210, 30, 20);

        lblMessageBottom = new JLabel();
        lblMessageBottom.setBounds(10, 210, 300, 20);


        this.getContentPane().add(lblMessage);
        this.getContentPane().add(lblMDP);
        this.getContentPane().add(lblChiffre);
        this.getContentPane().add(lblMinuscule);
        this.getContentPane().add(lblMajuscule);
        this.getContentPane().add(lblSpecial);
        this.getContentPane().add(chbChiffre);
        this.getContentPane().add(lblChiffre2);
        this.getContentPane().add(chbMinuscule);
        this.getContentPane().add(chbMajuscule);
        this.getContentPane().add(chbSpecial);
        this.getContentPane().add(lblNbCaractere);
        this.getContentPane().add(tfNbCaractere);
        this.getContentPane().add(btGeneration);
        this.getContentPane().add(btEnregistrer);
        this.getContentPane().add(tfMDP);
        this.getContentPane().add(tfMDP2);
        this.getContentPane().add(tfMDP2);
        this.getContentPane().add(lblMessageBottom);
        this.getContentPane().add(btMDPSaved);
        this.getContentPane().add(lblShowMDP);
        this.getContentPane().add(nbChiffreMini);
        this.getContentPane().add(chbShowMDP);



//        for (int i = 0; i < Integer.parseInt(longDefautMDP); i++) {
//            nbChiffreMini.addItem(i);
//        }


        chbShowMDP.addActionListener(this);

        this.estVisible();
    }

    public void initVariable() {
        chiffre = "0123456789";
        minuscule = "abcdefghijklmnopqrstuvwxyz";
        majuscule = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        special = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?";

        chaineCaractere = "";

        if (chbChiffre.isSelected()) {
            chaineCaractere += chiffre;
        }
        if (chbMinuscule.isSelected()) {
            chaineCaractere += minuscule;
        }
        if (chbMajuscule.isSelected()) {
            chaineCaractere += majuscule;
        }
        if (chbSpecial.isSelected()) {
            chaineCaractere += special;
        }

        longChaineCaractere = chaineCaractere.length();
    }

    public char tirageCaractere() {
        return chaineCaractere.charAt(tirageNombre(longChaineCaractere));
    }

    public int tirageNombre(int longueurChaine) {
        return (int) Math.floor(Math.random() * longueurChaine);
    }

    public String composerMDP(int longueur) {
        String resultat = new String();
        this.initVariable();

        if (longueur > 0) {
            for (int i = 0; i < longueur; i++) {
                resultat += tirageCaractere();
            }
        }
        return resultat;
    }

    public void estVisible() {
        if (chbShowMDP.isSelected()) {
            tfMDP2.setVisible(true);
            tfMDP.setVisible(false);
        } else {
            tfMDP2.setVisible(false);
            tfMDP.setVisible(true);
        }
    }

    public boolean isInt() {
        try {
            int i = Integer.parseInt(tfNbCaractere.getText());
            System.out.println("Est un nombre entier");
            return true;

        } catch (Exception ev) {
            System.out.println("N'est pas un nombre entier");
            tfNbCaractere.setText(String.valueOf(longDefautMDP));
            lblMessageBottom.setForeground(Color.red);
            lblMessageBottom.setText("Veuillez entrer un nombre entier");
            return false;
        }
    }

    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();

        if (action.equals(ACTION_GENERATION)) {
            if (isInt()) {
                actionGenerer();
            }
        }
        if (action.equals(ACTION_ENREGISTRER)) {
            actionEnregistrer();
        }
        if (action.equals(ACTION_MDPSAVED)) {
            AffichageMDP aMDP = new AffichageMDP(nomUser);
        }
        if (action.equals(ACTION_ESTVISIBLE)) {
            estVisible();
        }
    }

    public void actionGenerer() {
        if (Integer.parseInt(tfNbCaractere.getText()) <= longMaxMDP) {
            if (Integer.parseInt(tfNbCaractere.getText()) >= longMiniMDP) {
                int nbChar = Integer.parseInt(tfNbCaractere.getText());

                mdp = composerMDP(nbChar);
                tfMDP2.setText(mdp);
                tfMDP.setText(mdp);

                copyToClipboard(mdp);

                lblMessageBottom.setForeground(Color.green);
                lblMessageBottom.setText("Mot de passe copié");

            } else {
                afficheErreur();
            }

        } else {
            afficheErreur();
        }
    }

    public boolean checkAppli() {
        ConnectionBDD cbdd = ConnectionBDD.getInstance();
        connec = cbdd.getConnexion();

        String requete = "select application from mdp where application ='" + transfertMDP + "' and idUser = '"+ getIdUser() +"'";
        System.out.println(transfertMDP);
        Statement st;
        try {
            st = connec.createStatement();
            ResultSet rs = st.executeQuery(requete);

            while (rs.next()) {
                return true;
            }
        } catch (SQLException ex) {
            System.out.println("Erreur de selection dans la Base de Données : " + ex.getMessage());
        }
        return false;
    }

    public int getIdUser() {
        ConnectionBDD cbdd = ConnectionBDD.getInstance();
        connec = cbdd.getConnexion();

        String requete = "select idUser from user where login ='" + nomUser + "' ";

        Statement st;
        try {
            st = (Statement) connec.createStatement();
            ResultSet rs = st.executeQuery(requete);

            while (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException ex) {
            System.out.println("GetUserID() Erreur d'insertion d'informations dans la Base de Données : " + ex.getMessage());

        }
        return -1;
    }

    public boolean testConnection() {
        ConnectionBDD cbdd = ConnectionBDD.getInstance();
        connec = cbdd.getConnexion();

        String requete = "select * from user";

        Statement st;
        try {
            st = (Statement) connec.createStatement();
            st.executeQuery(requete);
            return true;
        } catch (SQLException ex) {
            System.out.println("testConnection() Erreur d'insertion d'informations dans la Base de Données : " + ex.getMessage());
        }
        return false;
    }

    public void actionEnregistrer() {
        if (tfMDP2.getText().length() != 0) {
            try {
                transfertMDP = JOptionPane.showInputDialog(lblMDP);

                if (!checkAppli()) {
                    if (transfertMDP.length() != 0) {
                        ConnectionBDD cbdd = ConnectionBDD.getInstance();
                        connec = cbdd.getConnexion();

                        String requete = "insert into mdp(idUser, mdp, application) values('" + getIdUser() + "','" + tfMDP2.getText() + "', '" + transfertMDP + "')";

                        Statement st;
                        try {
                            st = (Statement) connec.createStatement();
                            st.executeUpdate(requete);

                            lblMessageBottom.setForeground(Color.green);
                            lblMessageBottom.setText("Mot de passe enregistré");
                            System.out.println("Insertion réussie");
                        } catch (SQLException ex) {
                            lblMessageBottom.setForeground(Color.red);
                            lblMessageBottom.setText("Enregistrement échoué");
                            System.out.println("actionEnregistrer() Erreur d'insertion d'informations dans la Base de Données : " + ex.getMessage());

                        }
                    } else {
                        lblMessageBottom.setForeground(Color.red);
                        lblMessageBottom.setText("Spécifiez un nom pour la sauvegarde");
                    }
                } else {
                    lblMessageBottom.setForeground(Color.red);
                    lblMessageBottom.setText("Spécifiez un autre nom pour l'application");
                }
            } catch (NullPointerException npe) {
                lblMessageBottom.setForeground(Color.red);
                lblMessageBottom.setText("Enregistrement annulé");
            }
        } else {
            lblMessageBottom.setForeground(Color.red);
            lblMessageBottom.setText("Veuillez générer un mot de passe");
        }
    }

    public void afficheErreur() {
        JOptionPane.showMessageDialog(rootPane, "Choississez un nombre compris entre 5 et 50.");
        tfNbCaractere.setText(String.valueOf(longDefautMDP));
        tfMDP.setText("");
    }

    public void copyToClipboard(String text) {
        Toolkit toolKit = Toolkit.getDefaultToolkit();
        Clipboard cb = toolKit.getSystemClipboard();
        cb.setContents(new StringSelection(text), null);
    }
}


