package client.control.probleme;

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

import javax.swing.JOptionPane;

import reseau.DataNotFoundException;
import reseau.IDatabaseOperationsProxyFacade;
import reseau.IManagementOperationProxyFacade;
import reseau.IMathematicsOperationsProxyFacade;
import reseau.MathematicsException;
import reseau.OptimEISTIServerProxyFacade;
import reseau.UnauthorizedOperationException;
import client.Application;
import client.ApplicationHelper;
import client.model.problem.Contrainte;
import client.model.problem.Derive;
import client.model.problem.Methode;
import client.model.problem.Parameters;
import client.model.problem.Probleme;
import client.view.PanelGenerale;
import client.view.accueil.PanelAccueil;
import client.view.admin.PanelAdmin;
import client.view.member.PanelMembre;
import client.view.onglet.OngletSpecial;
import client.view.respoGroup.PanelRespoGroupe;

/** <u><b>Explication générale de la classe :</b></u>
 * <P> Cette classe permet de créer le controleur qui lance l'ensemble des processus de l'onglet problème
 *
 * @author Dream Team - ING2
 */
public class ControleurBoutonValiderProb implements ActionListener {

	PanelRespoGroupe prg = null;
	PanelMembre pm = null;
	
	public ControleurBoutonValiderProb() {}

	/** <u><i>Explication générale de la méthode :</i></u> 
	 * <P> Cette méthode permet de gérer les évènements liés à la souris
	 * 
	 * @param e Evènement de la souris
	 * 
	 */
	public void actionPerformed(ActionEvent e) {

		Component c = (Component) e.getSource();

		while (c != null) {
			if (c instanceof PanelRespoGroupe) {
				prg = (PanelRespoGroupe) c;
			} else if (c instanceof PanelMembre) {
				pm = (PanelMembre) c;
			}
			c = c.getParent();
		}

		String oldNomProbleme = new String();
		String nomProbleme = new String();
		String nomGroupe = new String();

		//Pour les responsables de groupe
		if (prg != null) {
			
			//On récupère le groupe
			nomGroupe = prg.getAccueil().getNomGroupe();
			int idGroup = Application.getInstance().getIdGroupe(nomGroupe);

			if (prg.getProbleme().getPanCreerPb().isVisible()) {
				
				//On récupère le problème pour vérifier s'il existe déjà un pb de même nom
				nomProbleme = prg.getProbleme().getPanCreerPb().getNomProbleme()
						.getText();
				int idProblemeExist = Application.getInstance().getIdProbleme(
						nomProbleme);
				
				try {
					//On récupère les problèmes à travers le réseau
					IManagementOperationProxyFacade mop = OptimEISTIServerProxyFacade.getInstance();
					Application.getInstance().updateArrayProbleme(mop.getProblems(Application.idSelect, idGroup));
				} catch (UnauthorizedOperationException ex) {
                    JOptionPane.showMessageDialog(null,
                            ex.getLocalizedMessage(),
                            "Impossible de mettre à jour les problèmes : interdit pour vous !",
                            JOptionPane.ERROR_MESSAGE);
                }catch (DataNotFoundException ed){
                	JOptionPane.showMessageDialog(null,
                            ed.getLocalizedMessage(),
                            "Erreur : Impossible de mettre à jour les problèmes !",
                            JOptionPane.ERROR_MESSAGE);
                }

                //On vérifie si l'idProbleme
				if (prg.getProbleme().getPanCreerPb().getNomProbleme()
						.getText().length() > 0
						&& !prg.getProbleme().getPanCreerPb().getNomProbleme()
								.getText().startsWith(" ") && idProblemeExist == -1) {
					prg.getProbleme().getPanChoixPb().getProblemeBox().addItem(
							prg.getProbleme().getPanCreerPb().getNomProbleme()
									.getText());

					//On récupère les champs
					String nomFonction = prg.getProbleme().getPanCreerPb()
							.getFonc().getText();
					String libelleFonction = prg.getProbleme().getPanCreerPb()
							.getFoncEnText().getText();
					String dimension = prg.getProbleme().getPanCreerPb()
							.getDimFoncEnText().getText();

					String appelFonction = prg.getProbleme().getPanCreerPb()
							.getvaluesListDefaultModelFonction().get(0)
							.toString().substring(2, prg.getProbleme().getPanCreerPb()
							.getvaluesListDefaultModelFonction().get(0)
							.toString().length());
					
					String solutionExacte = prg.getProbleme().getPanCreerPb().getSolProbleme().getText();

					//On crée un nouveau problème et on ajoute ses données
					Probleme newProbleme = new Probleme();
					
					newProbleme.setNomProbleme(nomProbleme);
					newProbleme.setLibelleFonction(libelleFonction);
					newProbleme.setNomFonction(nomFonction);
					newProbleme.setDimensionFonction(Integer.parseInt(dimension));
					newProbleme.setAppelFonction(appelFonction);
					newProbleme.setSolutionExacte(solutionExacte);

					for (int i = 0; i < prg.getProbleme().getPanCreerPb()
							.getValuesTableDefaultModelContrainte()
							.getRowCount(); i++) {
						if(i==0){
							Derive d = new Derive();
							d.addParameters(new Parameters(
									"representation-textuelle", (String) prg
											.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 3)));
							d.addParameters(new Parameters(
									"appel-fonction", (String) prg.getProbleme()
											.getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 2)));
							d.addParameters(new Parameters("chemin",
									(String) prg.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 1)));
							newProbleme.addDerive(d);
						}else{
							Contrainte contrainte = new Contrainte();
							contrainte.addParameters(new Parameters(
									"representation-textuelle", (String) prg
											.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 3)));
							contrainte.addParameters(new Parameters(
									"appel-fonction", (String) prg.getProbleme()
											.getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 2)));
							contrainte.addParameters(new Parameters("chemin",
									(String) prg.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 1)));
							newProbleme.addContraintes(contrainte);
						}
					}
										
					try {
						
						//On récupère le réseau
						IDatabaseOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
						
						newProbleme = dao.createProblem(Application.idSelect, idGroup, newProbleme);
						
						// On ajoute le problème dans le groupe et inversement
						Application.getInstance().getGroupe(nomGroupe).addIdProbleme(newProbleme.getIdProbleme());
						newProbleme.setIdGroup(idGroup);
						
						// On ajoute le problème dans l'arrayProbleme
						Application.getInstance().addProbleme(newProbleme.getIdProbleme(),
								newProbleme);
						
						// On MAJ les activités récentes
						Application.getInstance().getGroupe(nomGroupe).addActivity(
								"Problème " + nomProbleme + " créé");
						prg.getAccueil().getPanInfosRespoGroup()
								.getListOfActivite().setListData(
										Application.getInstance().getGroupe(
												nomGroupe).displayActivities());
						prg.getAccueil().getPanInfosRespoGroup().updateUI();
	
						// On MAJ les activités récentes
						Application.getInstance().getUser(Application.idSelect)
								.addActivity("Problème " + nomProbleme + " créé");
						PanelAccueil.getInstance().getListOfActivite().setListData(
								Application.getInstance().getUser(
										Application.idSelect).displayActivities());
						PanelAccueil.getInstance().updateUI();
	
						// On MAJ les box des problèmes
						int size = prg.getProbleme().getPanChoixPb()
								.getProblemeBox().getItemCount();
						prg.getProbleme().getPanChoixPb().remplirProblemeBox();
						prg.getProbleme().getPanChoixPb()
								.deleteItemOfGroupBox(size);
						prg.getProbleme().getPanChoixPb().updateUI();
	
						prg.getBenchmark().getPanBenchmarkPb().remplirProblemeBox();
						prg.getBenchmark().getPanBenchmarkRes().setVisible(false);
						prg.getBenchmark().getPanBenchmarkPb().updateUI();
	
						// On vide les panels et on affiche le bon
						prg.getProbleme().getPanCreerPb().ViderPanelCreer();
						prg.getProbleme().getPanCreerPb().setVisible(false);
						prg.getProbleme().getPanChoixPb().setVisible(true);
					
					} catch (UnauthorizedOperationException ex) {
                    
                		JOptionPane.showMessageDialog(null,
                            ex.getLocalizedMessage(),
                            "Impossible de créer un problème : interdit pour vous !",
                            JOptionPane.ERROR_MESSAGE);
                	}
					
				} else {
					JOptionPane
							.showMessageDialog(
									null,
									"Vous n'avez pas rempli le champs Nom Problème et/ou nom existant",
									"Erreur", JOptionPane.ERROR_MESSAGE);
				}
			}

			if (prg.getProbleme().getPanModifPb().isVisible()) {

				int option = JOptionPane.showConfirmDialog(prg, "La modification du problème entraînera la " +
						"suppression des résultats obtenus antérieurement. Voulez-vous continuer ?", "Modification d'un problème", JOptionPane.YES_NO_OPTION ,JOptionPane.QUESTION_MESSAGE);
				
				if(option != JOptionPane.NO_OPTION && option != JOptionPane.CLOSED_OPTION){
				
					//On récupère l'ancien et le nouveau nom du problème
					oldNomProbleme = prg.getProbleme().getPanChoixPb()
							.getProblemeBox().getSelectedItem().toString();
					nomProbleme = prg.getProbleme().getPanModifPb()
							.getNomProbleme().getText();
	
					if (prg.getProbleme().getPanModifPb().getNomProbleme()
							.getText().length() > 0
							&& !prg.getProbleme().getPanModifPb().getNomProbleme()
									.getText().startsWith(" ")) {
						prg.getProbleme().getPanChoixPb().getProblemeBox().addItem(
								prg.getProbleme().getPanModifPb().getNomProbleme()
										.getText());
						prg.getProbleme().getPanChoixPb().getProblemeBox().removeItem(
										prg.getProbleme().getPanChoixPb()
												.getProblemeBox().getSelectedItem());
	
						//On récupère les données
						String nomFonction = prg.getProbleme().getPanModifPb()
								.getFonc().getText();
						String libelleFonction = prg.getProbleme().getPanModifPb()
								.getFoncEnText().getText();
						String dimension = prg.getProbleme().getPanModifPb()
								.getDimFoncEnText().getText();
	
						//FIXME null case for appelFonction
						String appelFonction = ""; /*prg.getProbleme().getPanModifPb()
								.getvaluesListDefaultModelFonction().get(0)
								.toString();*/
						
						String solutionExacte = prg.getProbleme().getPanModifPb().getSolProbleme().getText();
	
						//On crée un problème avec le même id que celui courant et on met ses données
						Probleme pb = new Probleme();
						
						int idProbleme = Application.getInstance().getIdProbleme(
								oldNomProbleme);
	
						pb.setIdProbleme(idProbleme);
						pb.setNomProbleme(nomProbleme);
						pb.setLibelleFonction(libelleFonction);
						pb.setNomFonction(nomFonction);
						pb.setDimensionFonction(Integer.parseInt(dimension));
						pb.setAppelFonction(appelFonction);
						pb.setSolutionExacte(solutionExacte);
	
						for (int i = 0; i < prg.getProbleme().getPanModifPb()
								.getValuesTableDefaultModelContrainte()
								.getRowCount(); i++) {
							if(i==0){
								Derive d = new Derive();
								d.addParameters(new Parameters(
										"representation-textuelle", (String) pm
												.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 3)));
								d.addParameters(new Parameters(
										"appel-fonction", (String) pm.getProbleme()
												.getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 2)));
								d.addParameters(new Parameters("chemin",
										(String) pm.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 1)));
								pb.addDerive(d);
							}else{
								Contrainte contrainte = new Contrainte();
								contrainte.addParameters(new Parameters(
										"representation-textuelle", (String) prg
												.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 3)));
								contrainte.addParameters(new Parameters(
										"appel-fonction", (String) prg.getProbleme()
												.getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 2)));
								contrainte.addParameters(new Parameters("chemin",
										(String) prg.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 1)));
								pb.addContraintes(contrainte);
							}
						}
	
						try{
							
							//On recupère le réseau
							IDatabaseOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
							
							//On crée un problème un BDD
							Probleme newProbleme = dao.updateProblem(Application.idSelect, idGroup, pb);
							
							// On modifie le problème dans l'arrayProbleme
							Application.getInstance().addProbleme(newProbleme.getIdProbleme(),
									newProbleme);
		
							// On MAJ les activités récentes
							Application.getInstance().getGroupe(nomGroupe).addActivity(
									"Problème " + nomProbleme + " modifié");
							prg.getAccueil().getPanInfosRespoGroup()
									.getListOfActivite().setListData(
											Application.getInstance().getGroupe(
													nomGroupe).displayActivities());
							prg.getAccueil().getPanInfosRespoGroup().updateUI();
		
							// On MAJ les activités récentes
							Application.getInstance().getUser(Application.idSelect)
									.addActivity("Problème " + nomProbleme + " modifié");
							PanelAccueil.getInstance().getListOfActivite().setListData(
									Application.getInstance().getUser(
											Application.idSelect).displayActivities());
							PanelAccueil.getInstance().updateUI();
		
							// On MAJ les box des problèmes
							int size = prg.getProbleme().getPanChoixPb()
									.getProblemeBox().getItemCount();
							prg.getProbleme().getPanChoixPb().remplirProblemeBox();
							prg.getProbleme().getPanChoixPb()
									.deleteItemOfGroupBox(size);
							prg.getProbleme().getPanChoixPb().updateUI();
		
							prg.getBenchmark().getPanBenchmarkPb().remplirProblemeBox();
							prg.getBenchmark().getPanBenchmarkRes().setVisible(false);
							prg.getBenchmark().getPanBenchmarkPb().updateUI();
							
							prg.getProbleme().getPanConsultPb().remplirResultatBox();
							prg.getProbleme().getPanConsultPb().getScrollRes().setVisible(false);
							prg.getProbleme().getPanConsultPb().updateUI();
		
							prg.getProbleme().getPanModifPb().setVisible(false);
							prg.getProbleme().getPanChoixPb().setVisible(true);
							prg.getProbleme().getPanModifPb().ViderPanelModif();
						
						}catch (UnauthorizedOperationException ex){
	                        JOptionPane.showMessageDialog(null,
	                                ex.getLocalizedMessage(),
	                                "Impossible de modifier un problème : interdit pour vous !",
	                                JOptionPane.ERROR_MESSAGE);
	                    } catch (DataNotFoundException ed) {
	                    	JOptionPane.showMessageDialog(null,
	                                ed.getLocalizedMessage(),
	                                "Impossible de modifier un problème : problème non trouvé !",
	                                JOptionPane.ERROR_MESSAGE);
						}
					} else {
						JOptionPane
								.showMessageDialog(
										null,
										"Vous n'avez pas rempli le champs Nom Problème et/ou nom existant",
										"Erreur", JOptionPane.ERROR_MESSAGE);
					}
				}
			}

			if (prg.getProbleme().getPanExecPb().isVisible()) {

				// On recupère l'id du probleme
				nomProbleme = prg.getProbleme().getPanChoixPb()
						.getProblemeBox().getSelectedItem().toString();
				int idProbleme = Application.getInstance().getIdProbleme(
						nomProbleme);
				
				try{
					
					//On recupère le réseau
					IMathematicsOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
					
					int idMethode = Methode.getIdMethode(prg.getProbleme().getPanExecPb().getMethodes().getSelectedItem().toString());
					
					//Les conditions initiales
					ArrayList<Parameters> arrayCondiInit = new ArrayList<Parameters>();
					
					switch(idMethode){
						
						case Methode.ID_METHODE_PAS_FIXE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Step", prg.getProbleme().getPanExecPb().getStep().getText()));
							break;
						
						case Methode.ID_METHODE_PAS_OPTIMAL : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							break;
							
						case Methode.ID_METHODE_NEWTON : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Step", prg.getProbleme().getPanExecPb().getStep().getText()));
							break;
							
						case Methode.ID_METHODE_RECUIT_SIMULE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Temperature", prg.getProbleme().getPanExecPb().getTemperature().getText()));
							arrayCondiInit.add(new Parameters("Exploration-Step", prg.getProbleme().getPanExecPb().getExplorationStep().getText()));
							break;
							
						case Methode.ID_METHODE_TABOU :
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Exploration-Step", prg.getProbleme().getPanExecPb().getExplorationStep().getText()));
							break;
							
						case Methode.ID_METHODE_ALGO_EVOLUTIONNAIRE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Size-Of-Initial-Population", prg.getProbleme().getPanExecPb().getSizeOfInitialPop().getText()));
							arrayCondiInit.add(new Parameters("Cross-Probability", prg.getProbleme().getPanExecPb().getCrossProba().getText()));
							arrayCondiInit.add(new Parameters("Mutation-Probability", prg.getProbleme().getPanExecPb().getMutationProba().getText()));
							arrayCondiInit.add(new Parameters("Inferior-Limit", prg.getProbleme().getPanExecPb().getInf().getText()));
							arrayCondiInit.add(new Parameters("Superior-Limit", prg.getProbleme().getPanExecPb().getSup().getText()));
							break;

						default : System.out.println("No methods selected");
					}
					
					//Execute le probleme et on l'ajoute au cache
					dao.resolve(Application.idSelect, idGroup, idProbleme, arrayCondiInit, idMethode);
					
					// On MAJ les activités récentes
					Application.getInstance().getGroupe(nomGroupe).addActivity(
							"Problème " + nomProbleme + " exécuté");
					prg.getAccueil().getPanInfosRespoGroup().getListOfActivite()
							.setListData(
									Application.getInstance().getGroupe(nomGroupe)
											.displayActivities());
					prg.getAccueil().getPanInfosRespoGroup().updateUI();
	
					// On MAJ les activités récentes
					Application.getInstance().getUser(Application.idSelect)
							.addActivity("Problème " + nomProbleme + " exécuté");
					PanelAccueil.getInstance().getListOfActivite().setListData(
							Application.getInstance().getUser(Application.idSelect)
									.displayActivities());
					PanelAccueil.getInstance().updateUI();
	
					// On vide les panels et on affiche le bon
					prg.getProbleme().getPanExecPb().setVisible(false);
					prg.getProbleme().getPanChoixPb().setVisible(true);
					
	                //On met à jour les résultats
	                prg.getProbleme().getPanConsultPb().remplirResultatBox();
	                prg.getProbleme().getPanConsultPb().updateUI();
	                
	                //On débloque tout
	                DebloquerPanelRespo();
	                
				}catch (UnauthorizedOperationException ex) {
                    JOptionPane.showMessageDialog(null,
                            ex.getLocalizedMessage(),
                            "Impossible d'exècuter ce problème : interdit pour vous !",
                            JOptionPane.ERROR_MESSAGE);
                } catch (DataNotFoundException ed) {
                	JOptionPane.showMessageDialog(null,
                            ed.getLocalizedMessage(),
                            "Impossible d'exècuter ce problème : problème non trouvè !",
                            JOptionPane.ERROR_MESSAGE);
				} catch (MathematicsException em) {
					JOptionPane.showMessageDialog(null,
                            em.getLocalizedMessage(),
                            "Impossible d'exècuter ce problème : erreur mathèmatique !",
                            JOptionPane.ERROR_MESSAGE);
				}
			}
		// Pour les membres	
		} else if (pm != null) {

			//On récupère le groupe
			nomGroupe = pm.getAccueil().getNomGroupe();
			int idGroup = Application.getInstance().getIdGroupe(nomGroupe);

			if (pm.getProbleme().getPanCreerPb().isVisible()) {

				//On récupère le problème pour vérifier s'il existe déjà un pb de même nom
				nomProbleme = pm.getProbleme().getPanCreerPb().getNomProbleme()
						.getText();
				int idProblemeExist = Application.getInstance().getIdProbleme(
						nomProbleme);
				
				try {
					IManagementOperationProxyFacade mop = OptimEISTIServerProxyFacade.getInstance();
					Application.getInstance().updateArrayProbleme(mop.getProblems(Application.idSelect, idGroup));
				} catch (UnauthorizedOperationException ex) {
                    JOptionPane.showMessageDialog(null,
                            ex.getLocalizedMessage(),
                            "Impossible de mettre à jour les problèmes : interdit pour vous !",
                            JOptionPane.ERROR_MESSAGE);
                }catch (DataNotFoundException ed){
                	JOptionPane.showMessageDialog(null,
                            ed.getLocalizedMessage(),
                            "Erreur : Impossible de mettre à jour les problèmes !",
                            JOptionPane.ERROR_MESSAGE);
                }

				if (pm.getProbleme().getPanCreerPb().getNomProbleme().getText()
						.length() > 0
						&& !pm.getProbleme().getPanCreerPb().getNomProbleme()
								.getText().startsWith(" ") && idProblemeExist == -1) {
					pm.getProbleme().getPanChoixPb().getProblemeBox().addItem(
							pm.getProbleme().getPanCreerPb().getNomProbleme()
									.getText());

					//On récupère les données
					String nomFonction = pm.getProbleme().getPanCreerPb()
							.getFonc().getText();
					String libelleFonction = pm.getProbleme().getPanCreerPb()
							.getFoncEnText().getText();
					String dimension = pm.getProbleme().getPanCreerPb()
							.getDimFoncEnText().getText();

					String appelFonction = pm.getProbleme().getPanCreerPb()
					.getvaluesListDefaultModelFonction().get(0)
					.toString().substring(2, pm.getProbleme().getPanCreerPb()
					.getvaluesListDefaultModelFonction().get(0)
					.toString().length());
					
					String solutionExacte = pm.getProbleme().getPanCreerPb().getSolProbleme().getText();
								
					//On crée un problème et on met les données
					Probleme newProbleme = new Probleme();
					
					newProbleme.setNomProbleme(nomProbleme);
					newProbleme.setLibelleFonction(libelleFonction);
					newProbleme.setNomFonction(nomFonction);
					newProbleme.setDimensionFonction(Integer.parseInt(dimension));
					newProbleme.setAppelFonction(appelFonction);
					newProbleme.setSolutionExacte(solutionExacte);
					
					for (int i = 0; i < pm.getProbleme().getPanCreerPb()
							.getValuesTableDefaultModelContrainte()
							.getRowCount(); i++) {
						if(i==0){
							Derive d = new Derive();
							d.addParameters(new Parameters(
									"representation-textuelle", (String) pm
											.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 3)));
							d.addParameters(new Parameters(
									"appel-fonction", (String) pm.getProbleme()
											.getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 2)));
							d.addParameters(new Parameters("chemin",
									(String) pm.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 1)));
							newProbleme.addDerive(d);
						}else{
							Contrainte contrainte = new Contrainte();
							contrainte.addParameters(new Parameters(
									"representation-textuelle", (String) pm
											.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 3)));
							contrainte.addParameters(new Parameters(
									"appel-fonction", (String) pm.getProbleme()
											.getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 2)));
							contrainte.addParameters(new Parameters("chemin",
									(String) pm.getProbleme().getPanCreerPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 1)));
							newProbleme.addContraintes(contrainte);
						}
					}
					
					try {
						
						//On récupère le réseau
						IDatabaseOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
						
						newProbleme = dao.createProblem(Application.idSelect, idGroup, newProbleme);
						
						// On ajoute le problème dans le groupe et inversement
						Application.getInstance().getGroupe(nomGroupe).addIdProbleme(newProbleme.getIdProbleme());
						newProbleme.setIdGroup(idGroup);
						
						// On ajoute le problème dans l'arrayProbleme
						Application.getInstance().addProbleme(newProbleme.getIdProbleme(),
								newProbleme);
	
						// On MAJ les activités récentes
						Application.getInstance().getGroupe(nomGroupe).addActivity(
								"Problème " + nomProbleme + " créé");
						pm.getAccueil().getPanInfosMembre().getListOfActivite()
								.setListData(
										Application.getInstance().getGroupe(
												nomGroupe).displayActivities());
						pm.getAccueil().getPanInfosMembre().updateUI();
	
						// On MAJ les activités récentes
						Application.getInstance().getUser(Application.idSelect)
								.addActivity("Problème " + nomProbleme + " créé");
						PanelAccueil.getInstance().getListOfActivite().setListData(
								Application.getInstance().getUser(
										Application.idSelect).displayActivities());
						PanelAccueil.getInstance().updateUI();
	
						// On MAJ les box des problèmes
						int size = pm.getProbleme().getPanChoixPb()
								.getProblemeBox().getItemCount();
						pm.getProbleme().getPanChoixPb().remplirProblemeBox();
						pm.getProbleme().getPanChoixPb().deleteItemOfGroupBox(size);
						pm.getProbleme().getPanChoixPb().updateUI();
	
						pm.getBenchmark().getPanBenchmarkPb().remplirProblemeBox();
						pm.getBenchmark().getPanBenchmarkRes().setVisible(false);
						pm.getBenchmark().getPanBenchmarkPb().updateUI();
	
						pm.getProbleme().getPanCreerPb().ViderPanelCreer();
						pm.getProbleme().getPanCreerPb().setVisible(false);
						pm.getProbleme().getPanChoixPb().setVisible(true);
					
					} catch (UnauthorizedOperationException ex) {
                        JOptionPane.showMessageDialog(null,
                                ex.getLocalizedMessage(),
                                "Impossible de créer un problème : interdit pour vous !",
                                JOptionPane.ERROR_MESSAGE);
                    }
					
				} else {
					JOptionPane
							.showMessageDialog(
									null,
									"Vous n'avez pas rempli le champs Nom Problème et/ou nom existant",
									"Erreur", JOptionPane.ERROR_MESSAGE);
				}
			}

			if (pm.getProbleme().getPanModifPb().isVisible()) {

				int option = JOptionPane.showConfirmDialog(pm, "La modification du problème entraînera la " +
						"suppression des résultats obtenus antérieurement. Voulez-vous continuer ?", "Modification d'un problème", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				
				if(option != JOptionPane.CANCEL_OPTION && option != JOptionPane.CLOSED_OPTION){
				
					//On récupère le problème
					oldNomProbleme = pm.getProbleme().getPanChoixPb()
							.getProblemeBox().getSelectedItem().toString();
					nomProbleme = pm.getProbleme().getPanModifPb().getNomProbleme()
							.getText();
	
					if (pm.getProbleme().getPanModifPb().getNomProbleme().getText()
							.length() > 0
							&& !pm.getProbleme().getPanModifPb().getNomProbleme()
									.getText().startsWith(" ")) {
						pm.getProbleme().getPanChoixPb().getProblemeBox().addItem(
								pm.getProbleme().getPanModifPb().getNomProbleme()
										.getText());
						pm.getProbleme().getPanChoixPb().getProblemeBox().removeItem(
										pm.getProbleme().getPanChoixPb()
												.getProblemeBox().getSelectedItem());
	
						//On récupère les données
						String nomFonction = pm.getProbleme().getPanModifPb()
								.getFonc().getText();
						String libelleFonction = pm.getProbleme().getPanModifPb()
								.getFoncEnText().getText();
						String dimension = pm.getProbleme().getPanModifPb()
								.getDimFoncEnText().getText();
	
						//FIXME null case for appelFonction
						String appelFonction = ""; /*pm.getProbleme().getPanModifPb()
								.getvaluesListDefaultModelFonction().get(0)
								.toString();*/
						String solutionExacte = pm.getProbleme().getPanModifPb().getSolProbleme().getText();
	
						
						//On crée un problème pour mettre les modifs dedans
						Probleme pb = new Probleme();
	
						pb.setIdProbleme(Application.getInstance().getIdProbleme(
								oldNomProbleme));
						pb.setNomProbleme(nomProbleme);
						pb.setLibelleFonction(libelleFonction);
						pb.setNomFonction(nomFonction);
						pb.setDimensionFonction(Integer.parseInt(dimension));
						pb.setAppelFonction(appelFonction);
						pb.setSolutionExacte(solutionExacte);
	
						for (int i = 0; i < pm.getProbleme().getPanModifPb()
								.getValuesTableDefaultModelContrainte()
								.getRowCount(); i++) {
							if(i==0){
								Derive d = new Derive();
								d.addParameters(new Parameters(
										"representation-textuelle", (String) pm
												.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 3)));
								d.addParameters(new Parameters(
										"appel-fonction", (String) pm.getProbleme()
												.getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 2)));
								d.addParameters(new Parameters("chemin",
										(String) pm.getProbleme().getPanModifPb()
												.getValuesTableDefaultModelContrainte()
												.getValueAt(i, 1)));
								pb.addDerive(d);
							}else{
							Contrainte contrainte = new Contrainte();
							contrainte.addParameters(new Parameters(
									"representation-textuelle", (String) pm
											.getProbleme().getPanModifPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 3)));
							contrainte.addParameters(new Parameters(
									"appel-fonction", (String) pm.getProbleme()
											.getPanModifPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 2)));
							contrainte.addParameters(new Parameters("chemin",
									(String) pm.getProbleme().getPanModifPb()
											.getValuesTableDefaultModelContrainte()
											.getValueAt(i, 1)));
							pb.addContraintes(contrainte);
							}
						}
						
						try {
						
							//On recupère le réseau
							IDatabaseOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
							
							//On crée un problème un BDD
							Probleme newProbleme = dao.updateProblem(Application.idSelect, idGroup, pb);
							
							// On modifie le problème dans l'arrayProbleme
							Application.getInstance().addProbleme(newProbleme.getIdProbleme(),
									newProbleme);
							
							pm.getProbleme().getPanConsultPb().remplirResultatBox();
							pm.getProbleme().getPanConsultPb().getScrollRes().setVisible(false);
							pm.getProbleme().getPanConsultPb().updateUI();
							
							// On modifie le problème dans l'arrayProbleme
							Application.getInstance().addProbleme(pb.getIdProbleme(),
									pb);
		
							// On MAJ les activités récentes
							Application.getInstance().getGroupe(nomGroupe).addActivity(
									"Problème " + nomProbleme + " modifié");
							pm.getAccueil().getPanInfosMembre().getListOfActivite()
									.setListData(
											Application.getInstance().getGroupe(
													nomGroupe).displayActivities());
							pm.getAccueil().getPanInfosMembre().updateUI();
		
							// On MAJ les activités récentes
							Application
									.getInstance()
									.getUser(Application.idSelect)
									.addActivity("Problème " + nomProbleme + " modifié");
							PanelAccueil.getInstance().getListOfActivite().setListData(
									Application.getInstance().getUser(
											Application.idSelect).displayActivities());
							PanelAccueil.getInstance().updateUI();
		
							// On MAJ les box des problèmes
							int size = pm.getProbleme().getPanChoixPb()
									.getProblemeBox().getItemCount();
							pm.getProbleme().getPanChoixPb().remplirProblemeBox();
							pm.getProbleme().getPanChoixPb().deleteItemOfGroupBox(size);
							pm.getProbleme().getPanChoixPb().updateUI();
		
							pm.getBenchmark().getPanBenchmarkPb().remplirProblemeBox();
							pm.getBenchmark().getPanBenchmarkRes().setVisible(false);
							pm.getBenchmark().getPanBenchmarkPb().updateUI();
		
							pm.getProbleme().getPanModifPb().setVisible(false);
							pm.getProbleme().getPanChoixPb().setVisible(true);
							pm.getProbleme().getPanModifPb().ViderPanelModif();
						
						} catch (UnauthorizedOperationException ex) {
	                        JOptionPane.showMessageDialog(null,
	                                ex.getLocalizedMessage(),
	                                "Impossible de modifier un problème : interdit pour vous !",
	                                JOptionPane.ERROR_MESSAGE);
	                    } catch (DataNotFoundException ed) {
	                    	JOptionPane.showMessageDialog(null,
	                                ed.getLocalizedMessage(),
	                                "Impossible de modifier un problème : problème non trouvé !",
	                                JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			}

			if (pm.getProbleme().getPanExecPb().isVisible()) {

				nomProbleme = pm.getProbleme().getPanChoixPb()
				.getProblemeBox().getSelectedItem().toString();

				// On recupère l'id du probleme
				int idProbleme = Application.getInstance().getIdProbleme(
						nomProbleme);

				try{
					
					//On recupère le réseau
					IMathematicsOperationsProxyFacade dao = OptimEISTIServerProxyFacade.getInstance();
					
					int idMethode = Methode.getIdMethode(prg.getProbleme().getPanExecPb().getMethodes().getSelectedItem().toString());
					
					//On crée les conditions initiales
					ArrayList<Parameters> arrayCondiInit = new ArrayList<Parameters>();
					
					switch(idMethode){
						
						case Methode.ID_METHODE_PAS_FIXE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Step", prg.getProbleme().getPanExecPb().getStep().getText()));
							break;
						
						case Methode.ID_METHODE_PAS_OPTIMAL : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							break;
							
						case Methode.ID_METHODE_NEWTON : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Step", prg.getProbleme().getPanExecPb().getStep().getText()));
							break;
							
						case Methode.ID_METHODE_RECUIT_SIMULE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Temperature", prg.getProbleme().getPanExecPb().getTemperature().getText()));
							arrayCondiInit.add(new Parameters("Exploration-Step", prg.getProbleme().getPanExecPb().getExplorationStep().getText()));
							break;
							
						case Methode.ID_METHODE_TABOU :
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Iteration", prg.getProbleme().getPanExecPb().getIteration().getText()));
							arrayCondiInit.add(new Parameters("Exploration-Step", prg.getProbleme().getPanExecPb().getExplorationStep().getText()));
							break;
							
						case Methode.ID_METHODE_ALGO_EVOLUTIONNAIRE : 
							arrayCondiInit.add(new Parameters("Initial-Vector", prg.getProbleme().getPanExecPb().getInitialVector().getText()));
							arrayCondiInit.add(new Parameters("Epsilon", prg.getProbleme().getPanExecPb().getEpsilon().getText()));
							arrayCondiInit.add(new Parameters("Size-Of-Initial-Population", prg.getProbleme().getPanExecPb().getSizeOfInitialPop().getText()));
							arrayCondiInit.add(new Parameters("Cross-Probability", prg.getProbleme().getPanExecPb().getCrossProba().getText()));
							arrayCondiInit.add(new Parameters("Mutation-Probability", prg.getProbleme().getPanExecPb().getMutationProba().getText()));
							arrayCondiInit.add(new Parameters("Inferior-Limit", prg.getProbleme().getPanExecPb().getInf().getText()));
							arrayCondiInit.add(new Parameters("Superior-Limit", prg.getProbleme().getPanExecPb().getSup().getText()));
							break;

						default : System.out.println("No methods selected");
					}
					
					//Execute le problème et on l'ajoute
					dao.resolve(Application.idSelect, idGroup, idProbleme, arrayCondiInit, idMethode);
				
					// On MAJ les activités récentes
					Application.getInstance().getGroupe(nomGroupe).addActivity(
							"Problème " + nomProbleme + " exécuté");
					pm.getAccueil().getPanInfosMembre().getListOfActivite()
							.setListData(
									Application.getInstance().getGroupe(nomGroupe)
											.displayActivities());
					pm.getAccueil().getPanInfosMembre().updateUI();
	
					// On MAJ les activités récentes
					Application.getInstance().getUser(Application.idSelect)
							.addActivity("Problème " + nomProbleme + " exécuté");
					PanelAccueil.getInstance().getListOfActivite().setListData(
							Application.getInstance().getUser(Application.idSelect)
									.displayActivities());
					PanelAccueil.getInstance().updateUI();
	
					// On vide les panels et on affiche le bon
					pm.getProbleme().getPanExecPb().setVisible(false);
					pm.getProbleme().getPanChoixPb().setVisible(true);
					
					//On débloque tout
	                DebloquerPanelMembre();
                
				} catch (UnauthorizedOperationException ex) {
	                JOptionPane.showMessageDialog(null,
	                        ex.getLocalizedMessage(),
	                        "Impossible d'exècuter ce problème : interdit pour vous !",
	                        JOptionPane.ERROR_MESSAGE);
	            } catch (DataNotFoundException ed) {
                	JOptionPane.showMessageDialog(null,
                            ed.getLocalizedMessage(),
                            "Impossible d'exècuter ce problème : problème non trouvè !",
                            JOptionPane.ERROR_MESSAGE);
				} catch (MathematicsException em) {
					JOptionPane.showMessageDialog(null,
                            em.getLocalizedMessage(),
                            "Impossible d'exècuter ce problème : erreur mathèmatique !",
                            JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}
	
	/** <u><i>Explication générale de la méthode :</i></u> 
	 * <P> Cette méthode permet de débloquer les panels des responsable de groupe
	 * 
	 */
	public void DebloquerPanelRespo() {

        //On recupère l'onglet en cours
        OngletSpecial os = ((OngletSpecial) PanelGenerale.getInstance().getVueOnglet().getTabComponentAt(PanelGenerale.getInstance().getVueOnglet().getSelectedIndex()));

        int idUser = Application.idSelect;
        int idGroup = Application.getInstance().getIdGroupe(os.getTitle());
        int idRole = ApplicationHelper.IdRoleOfUserInGroup(idUser, idGroup);

        PanelGenerale.getInstance().getVueOnglet().setEnabled(true);
        if (ApplicationHelper.UserHaveGoodRole(idUser, idGroup, idRole)) {
            prg.getJtbOperation().setEnabled(true);
        } else if (ApplicationHelper.UserHaveGoodRole(Application.idSelect, idGroup, idRole)) {
            PanelAdmin.getInstance().setEnabled(true);
        }

        for (int i = 0; i < prg.getProbleme().getPanChoixPb().getComponentCount(); i++) {
            prg.getProbleme().getPanChoixPb().getComponent(i).setEnabled(true);
        }
    }
	
	/** <u><i>Explication générale de la méthode :</i></u> 
	 * <P> Cette méthode permet de débloquer les panels des membres
	 * 
	 */
	public void DebloquerPanelMembre() {

        //On recupère l'onglet en cours
        OngletSpecial os = ((OngletSpecial) PanelGenerale.getInstance().getVueOnglet().getTabComponentAt(PanelGenerale.getInstance().getVueOnglet().getSelectedIndex()));

        int idUser = Application.idSelect;
        int idGroup = Application.getInstance().getIdGroupe(os.getTitle());
        int idRole = ApplicationHelper.IdRoleOfUserInGroup(idUser, idGroup);

        PanelGenerale.getInstance().getVueOnglet().setEnabled(true);
        if (ApplicationHelper.UserHaveGoodRole(idUser, idGroup, idRole)) {
            pm.getJtbOperation().setEnabled(true);
        }

        for (int i = 0; i < pm.getProbleme().getPanChoixPb().getComponentCount(); i++) {
            pm.getProbleme().getPanChoixPb().getComponent(i).setEnabled(true);
        }
    }
}
