package Test;

import API.*;
import MNP.*;

// TODO: Trier ça pour faire un import par package utilisés (je n'ai pas eu le temps de le faire)
import javax.swing.*;
import java.awt.*;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Objects;

/**
 * Récupérer les actions des utilisateurs avec des ActionListener
 * et ListSelectionListener afin de lancer la vue demandée ou les
 * les fonctionnalitées demandées.
 */
public class Controller implements ActionListener, ListSelectionListener {
    private final BDatabase db;

    private ProfView pv;
    private AdminView av;
    private StudentView sv;
    private BFrame currentModal;
    private MainMenu parent;

    private ArrayList<Etudiant> e;
    private ArrayList<Groupe> g;
    private ArrayList<Requete> r;

    private JTable currentJTableUse;
    private JComboBox<String> list;
    private JComboBox<String> requestTypeSelector;

    private JTextArea content;
    private ArrayList<String> tmpStud;

    private JTextField l1;
    private JTextField l2;
    private JTextField l3;

    private String r1;
    private JTextField r2;

    public Controller(BDatabase db) {
        this.db = db;
        this.e = this.db.getEtuList();
        this.g = this.db.getGroupeList();
        this.r = this.db.getRequestList();
        this.sv = new StudentView(this.e, this.g, this);
        this.pv = new ProfView(this.e, this.g, this);
        this.av = new AdminView(this);
        this.parent = new MainMenu(this);
    }

    public Controller(BDatabase db, int selectedView) {
        this.db = db;
        this.e = this.db.getEtuList();
        this.g = this.db.getGroupeList();
        this.r = this.db.getRequestList();
        this.sv = new StudentView(this.e, this.g, this);
        this.pv = new ProfView(this.e, this.g, this);
        this.av = new AdminView(this);
        this.parent = new MainMenu(this, selectedView);
    }

    /**
     *
     * Récuperer le nombre de membres d'un groupe
     *
     * @param id le groupe
     * @return le nombre de membres
     */
    public int getMemberCount(int id) {
        int j = 0;

        for (int i = 0; i <= this.e.size() - 1; i++) {
            if (this.e.get(i).getGroupe() == id) {
                j++;
            }
        }

        return j;
    }

    /**
     * Pour créer une JTable
     * 
     * @param data  Les données
     * @param title Les titres
     */
    private JTable createJTable(Object[][] data, String[] title) {
        return new JTable(data, title) {
            public boolean editCellAt(int row, int column, java.util.EventObject e) {
                return false;
            }
        };
    }

    /**
     * Pour afficher une JTable sans listener
     *
     * @param liste La JTable
     */
    private void Display(JTable liste) {
        liste.getTableHeader().setReorderingAllowed(false);
        liste.setFillsViewportHeight(true);
        this.currentJTableUse = liste;
        this.parent.updateTable(liste);
    }

    /**
     * Pour afficher une JTable contenant un listener
     *
     * @param liste La JTable
     */
    private void DisplayWithListner(JTable liste) {
        ListSelectionModel lsm = liste.getSelectionModel();
        lsm.addListSelectionListener(this);
        liste.getTableHeader().setReorderingAllowed(false);
        liste.setFillsViewportHeight(true);

        this.currentJTableUse = liste;
        this.parent.updateTable(liste);
    }

    /**
     * Pour afficher une modale classique pour plus de libertées (panel a créer au
     * préalable)
     *
     * @param frameTitle Le titre de la fenêtre
     * @param size_x     Taille en x
     * @param size_y     Taille en y
     * @param loca_x     Localisation en x
     * @param loca_y     Localisation en y
     * @param forModal   Le panel a mettre dans la fenêtre (libre)
     */
    private void DisplayModal(String frameTitle, int size_x, int size_y, int loca_x, int loca_y, JPanel forModal) {
        this.currentModal = new BFrame(frameTitle, loca_x, loca_y, size_x, size_y, this.parent, forModal);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        String groupeOption = this.pv.getComboSelection();
        int groupeIndex = 0;
        String text = this.pv.getSearchStud();

        if (Objects.equals(command, "pv::GetStudList")) {
            String[][] data = new String[this.e.size()][2];

            String[] titre = {
                    "Nom",
                    "Prénom",
                    "Groupe"
            };

            for (int i = 0; i <= this.e.size() - 1; i++) {
                String[] info = {
                        this.e.get(i).getNom(),
                        this.e.get(i).getPrenom(),
                        this.getGroupeById(this.e.get(i).getGroupe())
                };

                data[i] = info;
            }

            Display(this.createJTable(data, titre));
        }

        else if (Objects.equals(command, "pv::GetListFiltered") ||
                Objects.equals(command, "sv::GetListFiltered")) {

            if (Objects.equals(command, "pv::GetListFiltered")) {
                groupeIndex = this.pv.getComboSelectionIndex();
            } else {
                groupeIndex = this.sv.getComboSelectionIndex();
            }

            String[][] data = new String[this.e.size()][1];

            String[] titre = {
                    "Nom",
                    "Prénom"
            };

            int i, j;

            for (i = 0, j = 0; i <= this.e.size() - 1; i++) {
                if (this.e.get(i).getGroupe() == groupeIndex) {
                    String[] info = {
                            this.e.get(i).getNom(),
                            this.e.get(i).getPrenom()
                    };

                    data[j] = info;
                    j++;
                }
            }

            String[][] data_final = new String[j][1];
            for (int x = 0; x <= j - 1; x++) {
                data_final[x] = data[x];
            }

            Display(this.createJTable(data_final, titre));
        }

        else if (Objects.equals(command, "pv::SearchStudentPer3Letters")) {
            if (text.length() < 3 || text == null) {
                JOptionPane.showMessageDialog(
                        this.pv,
                        "Veuillez écrire 3 lettres",
                        "Erreur.",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                char[] beg = text.toCharArray();

                ArrayList<String> filtreEleveNom = db
                        .fetchAll("SELECT nom FROM fi_eleves WHERE nom LIKE '" + beg[0] + beg[1] + beg[2] + "%'");
                ArrayList<String> filtreElevePrenom = db
                        .fetchAll("SELECT prenom FROM fi_eleves WHERE nom LIKE '" + beg[0] + beg[1] + beg[2] + "%'");
                ArrayList<String> filtreEleveGroupe = db
                        .fetchAll("SELECT groupe FROM fi_eleves WHERE nom LIKE '" + beg[0] + beg[1] + beg[2] + "%'");

                System.out.println(filtreEleveGroupe.size() + filtreElevePrenom.size() + filtreEleveGroupe.size());

                if (filtreEleveGroupe.size() == 0 || filtreEleveNom.size() == 0 || filtreElevePrenom.size() == 0) {
                    JOptionPane.showMessageDialog(
                            this.pv,
                            "Elève introuvable !",
                            "Erreur.",
                            JOptionPane.ERROR_MESSAGE);
                } else {
                    String[] titre = {
                            "Nom",
                            "Prénom",
                            "Groupe"
                    };

                    String[][] data = new String[filtreEleveNom.size()][2];

                    for (int i = 0; i <= filtreEleveNom.size() - 1; i++) {
                        data[i] = new String[] {
                                filtreEleveNom.get(i),
                                filtreElevePrenom.get(i),
                                String.valueOf(filtreEleveGroupe.get(i))
                        };
                    }

                    Display(this.createJTable(data, titre));
                }
            }
        }

        else if (Objects.equals(command, "av::MoveStudGrup")) {
            Object[][] data = new Object[this.e.size()][3];

            String[] titre = {
                    "Nom",
                    "Prénom",
                    "Groupe",
                    "Action"
            };

            for (int i = 0; i <= this.e.size() - 1; i++) {
                Object[] info = {
                        this.e.get(i).getNom(),
                        this.e.get(i).getPrenom(),
                        this.getGroupeById(this.e.get(i).getGroupe()),
                        "[DEPLACER]"
                };

                data[i] = info;
            }

            DisplayWithListner(this.createJTable(data, titre));
        }

        else if (Objects.equals(command, "av::AddStudGrup")) {
            ArrayList<ArrayList<String>> data = new ArrayList<>();

            String[] titre = {
                    "Nom",
                    "Prénom",
                    "Groupe",
                    "Action"
            };

            int i;

            for (i = 0; i <= this.e.size() - 1; i++) {
                if (this.e.get(i).getGroupe() == -1) {
                    ArrayList<String> info = new ArrayList<>();
                    info.add(this.e.get(i).getNom());
                    info.add(this.e.get(i).getPrenom());
                    info.add(this.getGroupeById(this.e.get(i).getGroupe()));
                    info.add("[AJOUTER]");

                    data.add(info);
                }
            }

            String[][] stringArray = data.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);

            DisplayWithListner(this.createJTable(stringArray, titre));
        }

        else if (Objects.equals(command, "crtll::ActionAddAndMoveGrup")) {
            this.tmpStud.add(String.valueOf(this.list.getSelectedIndex()));

            String query = "UPDATE fi_eleves SET groupe=" + this.tmpStud.get(2) +
                    " WHERE nom='" + this.tmpStud.get(0) +
                    "' AND prenom='" + this.tmpStud.get(1) + "'";

            System.out.println(query);

            if (db.updateRow(query)) {
                JOptionPane.showMessageDialog(
                        this.currentModal,
                        this.tmpStud.get(0) + " " + this.tmpStud.get(1) + " a bien ete deplace dans le "
                                + this.list.getSelectedItem(),
                        "Déplacement effectué",
                        JOptionPane.INFORMATION_MESSAGE);

                this.e = this.db.getEtuList();

                System.out.println(
                        "[+] Modification de " + this.tmpStud.get(1) + " " + this.tmpStud.get(0) + " effectue");
            } else {
                JOptionPane.showMessageDialog(
                        this.currentModal,
                        this.tmpStud.get(0) + " " + this.tmpStud.get(1) + " n'a pas pu etre deplace",
                        "Erreur lors du déplacement",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

        else if (Objects.equals(command, "sv::GetGrup")) {
            String[][] data = new String[this.g.size()][];

            String[] title = new String[] {
                    "ID", "Nom", "Taille"
            };

            for (int i = 0; i <= this.g.size() - 1; i++) {
                data[i] = new String[] {
                        String.valueOf(this.g.get(i).getId()),
                        this.g.get(i).getName(),
                        this.getMemberCount(i) + "/" + this.g.get(i).getMax()
                };
            }

            DisplayWithListner(this.createJTable(data, title));
        }

        else if (Objects.equals(command, "sv::MakeRequest")) {
            JPanel forModal = new JPanel(new GridBagLayout());
            BLayout settings = new BLayout();
            settings.setPositionY(0);
            settings.setPositionX(0);

            /**
             * TODO:
             * - Demande de type...
             * - Vers quel groupe
             * - possible ou nn
             * - message
             * - Valider
             */

            settings.setPositionY(1);
            JLabel requestT = new JLabel("Dans quel groupe souhaitez-vous aller ?");
            forModal.add(requestT, settings);

            settings.setPositionY(2);
            this.requestTypeSelector = new JComboBox<>();

            for (int i = 0; i <= this.g.size() - 1; i++) {
                this.requestTypeSelector.addItem(this.g.get(i).getName());
            }

            forModal.add(this.requestTypeSelector, settings);

            settings.setPositionY(3);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(4);
            this.content = new JTextArea();
            this.content.setPreferredSize(new Dimension(450, 250));
            forModal.add(this.content, settings);

            settings.setPositionY(5);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(6);
            CustomJButton confirmRequ = new CustomJButton("Envoyer");
            confirmRequ.addActionListener(this);
            confirmRequ.setActionCommand("sv::SendRequest");
            forModal.add(confirmRequ, settings);

            DisplayModal(
                    "Veuillez entrer un message...",
                    750,
                    500,
                    this.parent.getLocation().x + (this.parent.getSize().width - 750) / 2,
                    this.parent.getLocation().y + (this.parent.getSize().height - 500) / 2,
                    forModal);
        }

        else if (Objects.equals(command, "sv::SendRequest")) {
            int groupe = (int) this.requestTypeSelector.getSelectedIndex();
            String message = this.content.getText();
            System.out.println(groupe);

            // Etudiant qui est supposé utiliser cette vue
            Etudiant forTest = new EtudiantNP("Boudjemline", "Bilal", -1);
            int id = 115;
            int x = this.getMemberCount(-1);
            int type;
            int y = this.getMemberCount(groupe);

            if (x > y || x == y) { // Type 1
                type = 1;
            } else { // Type 2
                type = 2;
            }

            this.db.updateRow("ALTER TABLE fi_demandes AUTO_INCREMENT = " + this.r.size());

            if (this.db.insertRow("fi_demandes", new String[] {
                    "id_eleve", "id_groupe", "message", "type" },
                    new String[] {
                            String.valueOf(id), String.valueOf(groupe), message, String.valueOf(type)
                    })) {
                JOptionPane.showMessageDialog(
                        this.pv,
                        "Votre requête a été envoyé avec succès !",
                        "Requête.",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(
                        this.sv,
                        "Une erreur est survenue lors de l'envoi de votre message...\nVeuillez réessayer plus tard.",
                        "Erreur avec la base de données.",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

        else if (Objects.equals(command, "sv::ShowRequest")) {
            JPanel forModal = new JPanel();
            int nbMessage;
            int moi = 115;

            ArrayList<String> idm = this.db.fetchAll("SELECT id FROM fi_demandes WHERE id_eleve = " + moi);
            ArrayList<String> message = this.db.fetchAll("SELECT message FROM fi_demandes WHERE id_eleve = " + moi);
            ArrayList<String> statut = this.db.fetchAll("SELECT statut FROM fi_demandes WHERE id_eleve = " + moi);

            Object[][] data = new Object[idm.size()][];

            String[] title = new String[] {
                    "ID", "Contenu", "Statut"
            };

            for (int i = 0; i <= idm.size() - 1; i++) {
                String[] info = {
                        "#" + idm.get(i), message.get(i), statut.get(i)
                };

                data[i] = info;
            }

            Display(this.createJTable(data, title));
        }

        else if (Objects.equals(command, "av::CreateGrup")) {
            JPanel forModal = new JPanel(new GridBagLayout());
            BLayout settings = new BLayout();
            settings.setPositionX(0);

            settings.setPositionY(1);
            forModal.add(new JLabel("Nom du groupe (EXEMPLE: Groupe du soleil)"), settings);

            settings.setPositionY(2);
            this.l1 = new JTextField();
            this.l1.setPreferredSize(new Dimension(130, 30));
            forModal.add(this.l1, settings);

            settings.setPositionY(3);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(4);
            forModal.add(new JLabel("Taille maximum (uniquement des chiffres)"), settings);

            settings.setPositionY(5);
            this.l2 = new JTextField();
            this.l2.setPreferredSize(new Dimension(30, 30));
            forModal.add(this.l2, settings);

            settings.setPositionY(6);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(7);
            forModal.add(new JLabel("Taille minimum (uniquement des chiffres)"), settings);

            settings.setPositionY(8);
            this.l3 = new JTextField();
            this.l3.setPreferredSize(new Dimension(30, 30));
            forModal.add(this.l3, settings);

            settings.setPositionY(9);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(10);
            forModal.add(new JLabel(" "), settings);

            settings.setPositionY(11);
            CustomJButton create = new CustomJButton("Créer");
            create.addActionListener(this);
            create.setActionCommand("av::CreateGrupOnDatabase");
            forModal.add(create, settings);

            DisplayModal(
                    "Creation de groupe",
                    750,
                    500,
                    this.parent.getLocation().x + (this.parent.getSize().width - 750) / 2,
                    this.parent.getLocation().y + (this.parent.getSize().height - 500) / 2,
                    forModal);
        }

        else if (Objects.equals(command, "av::CreateGrupOnDatabase")) {
            String nom = this.l1.getText();
            String max = this.l2.getText();
            String min = this.l3.getText();

            this.db.updateRow("ALTER TABLE fi_groupe AUTO_INCREMENT=" + this.g.size());

            if (this.db.insertRow("fi_groupe", new String[] { "nom", "min", "max" }, new String[] { nom, min, max })) {
                JOptionPane.showMessageDialog(
                        this.parent,
                        "Groupe " + nom + " crée !",
                        "Succes",
                        JOptionPane.INFORMATION_MESSAGE);

                this.g = this.db.getGroupeList();
            } else {
                JOptionPane.showMessageDialog(
                        this.parent,
                        "La creation du groupe : " + nom + " à échoué.",
                        "Erreur",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

        else if (Objects.equals(command, "av::renameGrup")) {
            Object[][] data = new Object[this.g.size()][2];

            String[] titre = {
                    "Groupes",
                    " "
            };

            for (int i = 0; i <= this.g.size() - 1; i++) {
                Object[] info = {
                        this.g.get(i).getName(),
                        "[RENOMMER]"
                };

                data[i] = info;
            }

            DisplayWithListner(this.createJTable(data, titre));
        }

        else if (Objects.equals(command, "crtll::RenameGrup")) {
            String grupToChange = this.r1;
            String newName = this.r2.getText();

            if (this.db.updateRow("UPDATE fi_groupe SET nom='" + newName + "' WHERE nom = '" + grupToChange + "'")) {
                JOptionPane.showMessageDialog(
                        this.parent,
                        "Le groupe : " + grupToChange + " a bien ete renommé par : " + newName,
                        "Succes",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(
                        this.parent,
                        "Echec du changement de nom du groupe : " + grupToChange,
                        "Erreur",
                        JOptionPane.ERROR_MESSAGE);
            }

            this.g = this.db.getGroupeList();
        }

        else if (Objects.equals(command, "av::delGrup")) {
            Object[][] data = new Object[this.g.size()][2];

            String[] titre = {
                    "Groupes",
                    " "
            };

            for (int i = 0; i <= this.g.size() - 1; i++) {
                Object[] info = {
                        this.g.get(i).getName(),
                        "[SUPPRIMER]"
                };

                data[i] = info;
            }

            DisplayWithListner(this.createJTable(data, titre));
        }

        else if (Objects.equals(command, "av::ShowRequestFromStudent")) {
            showRequest();
        }
    }

    private void showRequest() {
        this.r = this.db.getRequestList();
        ArrayList<ArrayList<String>> data = new ArrayList<>();

        String[] titre = {
                "Id",
                "Etudiant",
                "Groupe demande",
                "Message",
                "Type",
                "Action"
        };

        for (int i = 0; i <= this.r.size() - 1; i++) {
            if (this.r.get(i).getStatut().equals("Pas encore de reponse")) {
                ArrayList<String> info = new ArrayList<>();
                info.add(this.r.get(i).getIdMessage() + "");
                info.add(this.getEtuNameById(this.r.get(i).getEtuId()));
                info.add(this.getGroupeById(this.r.get(i).getWitchGroupe()));
                info.add(this.r.get(i).getMessage());
                info.add(this.r.get(i).getType() + "");
                info.add("[DECISION]");

                data.add(info);
            }
        }

        String[][] stringArray = data.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);

        DisplayWithListner(this.createJTable(stringArray, titre));
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            int[] cell = this.currentJTableUse.getSelectedRows();
            int collumnCount = this.currentJTableUse.getColumnCount();
            Object value;

            if (cell.length > 0) {
                for (int i = 0; i < collumnCount; i++) {
                    TableModel tm = this.currentJTableUse.getModel();
                    value = tm.getValueAt(cell[0], i);

                    if (Objects.equals(value, "[DEPLACER]")) {
                        addMoveStudent(tm, cell, "[DEPLACER]");
                    }

                    else if (Objects.equals(value, "[AJOUTER]")) {
                        addMoveStudent(tm, cell, "[AJOUTER]");
                    }

                    else if (Objects.equals(value, "[RENOMMER]")) {
                        renameGrup(tm, cell);
                    }

                    else if (Objects.equals(value, "[SUPPRIMER]")) {
                        deleteGrup(tm, cell);
                    }

                    else if (Objects.equals(value, "[DECISION]")) {
                        makeDecision(tm, cell);
                    }
                }
            }
        }
    }

    public String getEtuNameById(int id) {
        String nom = this.db.fetchAll("SELECT nom FROM fi_eleves WHERE id = " + id).get(0);
        String prenom = this.db.fetchAll("SELECT prenom FROM fi_eleves WHERE id = " + id).get(0);

        return nom + " " + prenom;
    }

    private void makeDecision(TableModel tm, int[] cell) {
        int choice = JOptionPane.showConfirmDialog(this.parent, "Accepter la demande ?");
        int idDestinationGroup  = getIDGroupeByName((String) tm.getValueAt(cell[0], 2));
        String idMessage = (String) tm.getValueAt(cell[0], 0);
        String idEleve = this.db.fetchAll("SELECT id_eleve FROM fi_demandes WHERE id = " + idMessage).get(0);

        if (choice == 0) {
            if (this.db.updateRow("UPDATE fi_demandes SET statut = 'Acceptée' WHERE id = " + idMessage)) {
                if (this.db.updateRow("UPDATE fi_eleves SET groupe = " + idDestinationGroup + " WHERE id = " + idEleve)) {
                    JOptionPane.showMessageDialog(
                            this.parent,
                            "La demande a bien été acceptée",
                            "Succès",
                            JOptionPane.INFORMATION_MESSAGE);
                    this.showRequest();
                } else {
                    JOptionPane.showMessageDialog(
                            this.parent,
                            "Echec de validation",
                            "Echec",
                            JOptionPane.ERROR_MESSAGE);
                }

            } else {
                JOptionPane.showMessageDialog(
                        this.parent,
                        "Impossible d'accepter la demande",
                        "Echec",
                        JOptionPane.ERROR_MESSAGE);
            }

        } else if (choice == 1){
            if (this.db.updateRow("UPDATE fi_demandes SET statut = 'Refusée' WHERE id = " + idDestinationGroup)) {
                JOptionPane.showMessageDialog(
                this.parent,
                "La demande a bien été refusée",
                "Succes",
                JOptionPane.INFORMATION_MESSAGE);

            } else {
                JOptionPane.showMessageDialog(
                this.parent,
                "Impossible de refuser la demande",
                "Echec",
                JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void deleteGrup(TableModel tm, int[] cell) {
        int choice = JOptionPane.showConfirmDialog(this.parent, "Etes-vous sur ?");

        if (choice == 0) {
            String grupDelName = (String) tm.getValueAt(cell[0], 0);

            if (this.db.updateRow("DELETE FROM fi_groupe WHERE nom = '" + grupDelName + "'")) {
                if (this.db.updateRow("UPDATE fi_eleves SET groupe = -1 WHERE groupe = " + this.getIDGroupeByName(grupDelName))) {
                    this.e = this.db.getEtuList();
                    this.g = this.db.getGroupeList();

                    JOptionPane.showMessageDialog(
                            this.parent,
                            "Le groupe : " + grupDelName + " a bien ete supprime",
                            "Succes",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(
                            this.parent,
                            "Echec de la suppression du groupe : " + grupDelName,
                            "Erreur",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }

        this.parent.updateTable(this.initTable());
    }

    private void renameGrup(TableModel tm, int[] cell) {
        this.r1 = (String) tm.getValueAt(cell[0], 0);

        JPanel forModal = new JPanel(new GridBagLayout());
        BLayout settings = new BLayout();
        settings.setPositionX(0);

        settings.setPositionY(0);
        forModal.add(new JLabel("Nouveau nom"), settings);

        settings.setPositionY(1);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionY(2);
        this.r2 = new JTextField();
        this.r2.setPreferredSize(new Dimension(130, 30));
        forModal.add(this.r2, settings);

        settings.setPositionY(3);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionY(4);
        forModal.add(new JLabel(" "), settings);

        JButton confirmRename = new JButton("Renommer");
        confirmRename.addActionListener(this);
        confirmRename.setActionCommand("crtll::RenameGrup");
        forModal.add(confirmRename, settings);

        DisplayModal(
                "Renommer le groupe",
                600,
                300,
                this.parent.getLocation().x + (this.parent.getSize().width - 600) / 2,
                this.parent.getLocation().y + (this.parent.getSize().height - 300) / 2,
                forModal);

        this.g = this.db.getGroupeList();
        this.parent.updateTable(this.initTable());
    }

    private void addMoveStudent(TableModel tm, int[] cell, String action) {
        String[] stringSetAdd = {
                "Ajouter ",
                "Ajouter",
                "Nouveau groupe de l'élève : "
        };

        String[] stringSetMove = {
                "Déplacer ",
                "Déplacer",
                "Déplacer l'élève : "
        };

        String[] stringSet;

        if (action == "[AJOUTER]") {
            stringSet = stringSetAdd;
        } else {
            stringSet = stringSetMove;
        }

        JPanel forModal = new JPanel(new GridBagLayout());
        BLayout settings = new BLayout();

        this.tmpStud = new ArrayList<>();
        this.tmpStud.add((String) tm.getValueAt(cell[0], 0));
        this.tmpStud.add((String) tm.getValueAt(cell[0], 1));

        settings.setPositionX(0);
        settings.setPositionY(0);
        JLabel intro = new JLabel(
                stringSet[0] + tm.getValueAt(cell[0], 0) + " " +
                        tm.getValueAt(cell[0], 1) +
                        " dans le groupe : ");
        forModal.add(intro, settings);

        settings.setPositionX(1);
        settings.setPositionY(0);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionX(2);
        settings.setPositionY(0);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionX(3);
        settings.setPositionY(0);

        this.list = new JComboBox<>();

        for (Groupe groupe : this.g) {
            this.list.addItem(groupe.getName());
        }

        forModal.add(list, settings);

        settings.setPositionX(4);
        settings.setPositionY(0);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionX(5);
        settings.setPositionY(0);
        forModal.add(new JLabel(" "), settings);

        settings.setPositionX(6);
        settings.setPositionY(0);
        JButton moveBtn = new JButton(stringSet[1]);
        moveBtn.setActionCommand("crtll::ActionAddAndMoveGrup");
        moveBtn.addActionListener(this);
        forModal.add(moveBtn, settings);

        DisplayModal(
                stringSet[2]
                        + tm.getValueAt(cell[0], 0) + " " + tm.getValueAt(cell[0], 1),
                500,
                250,
                this.parent.getLocation().x + (this.parent.getSize().width - 500) / 2,
                this.parent.getLocation().y + (this.parent.getSize().height - 250) / 2,
                forModal);

        this.g = this.db.getGroupeList();
        this.parent.updateTable(this.initTable());
    }

    public JTable initTable() {
        this.e = this.db.getEtuList();
        this.g = this.db.getGroupeList();

        Object[][] data = new Object[this.e.size()][3];
        String[] title = {
                "Nom",
                "Prénom",
                "Groupe",
        };
        for (int i = 0; i <= this.e.size() - 1; i++) {
            Object[] info = {
                    this.e.get(i).getNom(),
                    this.e.get(i).getPrenom(),
                    this.getGroupeById(this.e.get(i).getGroupe())
            };

            data[i] = info;
        }
        return createJTable(data, title);
    }

    public String getGroupeById(int id) {
        if (id != -1) {
            return this.db.fetchAll("SELECT nom FROM fi_groupe WHERE id = " + id).get(0);
        } else {
            return "PAS DE GROUPE";
        }
    }

    public int getIDGroupeByName(String label) {
        for (int i = 0; i <= this.g.size() - 1; i++) {
            if (this.g.get(i).getName().equals(label)) {
                return this.g.get(i).getId();
            }
        }

        return -1;
    }

    public ProfView getProfView() {
        return this.pv;
    }

    public StudentView getStudentView() {
        return this.sv;
    }

    public AdminView getAdminView() {
        return this.av;
    }

    public ArrayList<Etudiant> getEtudiants() {
        return this.e;
    }

    public ArrayList<Groupe> getGroupes() {
        return this.g;
    }

    public BDatabase getDatabase() {
        return this.db;
    }

    public void setEtudiants(ArrayList<Etudiant> e) {
        this.e = e;
    }

    public void setGroupes(ArrayList<Groupe> g) {
        this.g = g;
    }

    public void setRequest(ArrayList<Requete> r) {
        this.r = r;
    }

    public void setMainMenu(MainMenu m) {
        this.parent = m;
    }
}
