Skip to content
Snippets Groups Projects
mainManager.cs 36.43 KiB
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Windows;
using static ChargementJSONStructure;
using static EpreuveCondition;

public class mainManager : MonoBehaviour
{
    public NewSystemeDeTraces newSystemeDeTraces;
    public ChargementJSONStructure jsonStructureScript;
    public AudioSource mainAudioSource;
    public int currentSession = 0;
    public string dateWhenSessionWasLaunched;
    public int scoreSession = 0;
    public int currentEpreuve = 0;
    public int scoreEpreuve = 0;
    public int currentItem = 0;
    public int scoreItem = 0;
    private int currentChoix = 0;
    public ChargementJSONStructure.Session s;
    public ChargementJSONStructure.Epreuve e;
    public ChargementJSONStructure.EpreuveItem i;
    public ChargementJSONStructure.Choix c;
    public bool playerTurn = false;
    public int current_step;
    public Positionnement posScript;
    private Coroutine playsoundCoroutine;
    private bool boutonCheatNext = false;
    public Image boutonCheatNextImage;
    private bool OnGoingTapToUnlockCheat = false;
    public TextMeshProUGUI texteCheat;
    private int compteurclickcoinDroitHautToUnlockCheat = 0;
    public bool sessionConsignebeenPlayed = false;
    public bool epreuveConsignebeenPlayed = false;
    public float user_dureeActionOnChoix = 0.0f;
    public string user_choix;
    public string[] user_choixPossibles;
    public string[] user_choix_ChoisiDansLordre;
    public GameObject fondNoirImage;
    public float actionUtilisateurStartTimeItem=0.0f;
    public List<groupemementChoixEtPrefabBoutonQCM> list_choix_associed_with_prefabs;
    private string dernierChoixAudioclip;
    public GD_manager gdmanager;
    public QCM_manager qcmmanager;
    public GameObject oreilleListen;
    public listenAnim oreilleListenScript;
    public GestionProgression gestionProg;
    public string clefPourSauvegardeUtilisateur;
    private int durePauseBannissementEnMinutes = 20;
    private bool bannissementIsOn;
    private bool bannissementIsOver;
    private DateTime bannissementExpirationDateTime;
    public TextMeshProUGUI texteSessionQuestionNumero;
    public class groupemementChoixEtPrefabBoutonQCM
    {
        public ChargementJSONStructure.Choix choix;
        public boutonQCM boutonqcmAssocied;
        public elementGD elementGDAssocied;
        public dropZoneGD elementDropZoneAssocied;
    }
    void Start()
    {
        // ENVOI TRACES SERVEUR : si on voit que ce joueur a des .json traces dans le dossier TracesToBeSent, on les envoit (sinon on les envoit en fin d'epreuves)
        Debug.Log("start");
        resetClasse();
        currentSession = 0;
        Time.timeScale = 1.0f;
        bannissementIsOn = false;
        bannissementIsOver = false;
        // Vérifier si la clé existe dans le dictionnaire
        clefPourSauvegardeUtilisateur = "gm2024E";

        if (HM_DataController.currentTeacherAccount != null && HM_DataController.currentChildUser!=null)
        {
            clefPourSauvegardeUtilisateur = HM_DataController.currentTeacherAccount.teacherCode.ToString() + HM_DataController.currentChildUser.userID.ToString();

        }
        List<DonneesProgression> listeSauvegardes = gestionProg.ChargerSauvegardes().listeDeDonnees;
        bool reffound = false;
        foreach(DonneesProgression dp in listeSauvegardes)
        {
            Debug.Log("clef here = " + dp.clef);
            if (dp.clef == clefPourSauvegardeUtilisateur)
            {
                reffound = true;
                Debug.Log("FOUND starting with session N °" + dp.NumeroSession);
                currentSession = dp.NumeroSession;
                break;
            }
        }
        if (!reffound)
        {
            Debug.Log("CLEF "+ clefPourSauvegardeUtilisateur +" NOT FOUND starting with session N °0");
        }
        toutessessionsacheves = false;

        string AttributBannissement = "bannissement_" + NewSystemeDeTraces.returnUserIDFLuence_or_UserIDHM();

        if (PlayerPrefs.HasKey(AttributBannissement))
        {
            string timestampString = PlayerPrefs.GetString(AttributBannissement);
            if (!string.IsNullOrEmpty(timestampString))
            {
                DateTime timestampDateTime;
                bool parseSuccess = DateTime.TryParseExact(timestampString, "yyyy-MM-dd HH:mm", null, System.Globalization.DateTimeStyles.None, out timestampDateTime);
                if (parseSuccess)
                {
                    Debug.Log("Timestamp récupéré : " + timestampDateTime);
                    bannissementExpirationDateTime = timestampDateTime.AddMinutes(20);
                    DateTime now = DateTime.Now;
                    if (now < bannissementExpirationDateTime)
                    {
                        bannissementIsOn = true;
                    }
                    // Tu peux maintenant utiliser timestampDateTime comme un objet DateTime
                }
                else
                {
                    Debug.LogError("Erreur lors de la conversion du timestamp.");
                }
            }
        }
        s = jsonStructureScript.data.sessions[currentSession];
        if (currentSession >= jsonStructureScript.data.sessions.Count)
        {
            toutessessionsacheves = true;
            Debug.Log("Current session is done ");
            currentSession = jsonStructureScript.data.sessions.Count-1;
            s = jsonStructureScript.data.sessions[currentSession];
            currentEpreuve = s.epreuves.Count - 1;
            e = s.epreuves[currentEpreuve];
            if (e.nbItemsMax == 0 && e.items != null)
            {
                e.nbItemsMax = e.items.Count;
            }
            currentItem = e.items.Count - 1;
            i = e.items[currentItem];
            ouvrirMenu(false);
        }
        else if (bannissementIsOn)
        {
            ouvrirMenu(false);
        }
        else
        {
            //playSteps();
            Debug.Log("nextstep from start function");
            nextEpreuve(true);
        }

    }
    private int compteurdeclickOnBoutonRAZ = 0;
    public TextMeshProUGUI boutonDeconnexionText;
    private bool deconnexionPlusRAZ;

    public void boutonRAZPlayerprefsForthisuserClicked()
    {
        Debug.Log("boutonRAZPlayerprefsForthisuserClicked");
        compteurdeclickOnBoutonRAZ++;
        if (compteurdeclickOnBoutonRAZ >= 15 && compteurdeclickOnBoutonRAZ<20)
        {
            deconnexionPlusRAZ = true;
            boutonDeconnexionText.text = "Déconnecter + RAZ progression";
            boutonDeconnexion.SetActive(true);

            if (bannissementIsOn)
            {
                BoutonnextsessionTexte.text = "Lancer la session";
                boutonSessionSuivante.SetActive(true);
            }

        }
        else if (compteurdeclickOnBoutonRAZ >= 20)
        {
            deconnexionPlusRAZ = false;
            boutonDeconnexionText.text = "Déconnecter l'utilisateur sans RAZ progression";
            compteurdeclickOnBoutonRAZ = 0;
        }
    }
    private void resetClasse()
    {
        actionUtilisateurStartTimeItem = 0.0f;
        playerTurn = false;
        dateWhenSessionWasLaunched = newSystemeDeTraces.GetFormattedDate() + "-" + newSystemeDeTraces.GetTimeAsString();
        currentSession = 0;
        sessionConsignebeenPlayed = false;
        epreuveConsignebeenPlayed = false;
        boutonCheatNext = false;
        compteurclickcoinDroitHautToUnlockCheat = 0;
        scoreSession = 0;
        currentEpreuve = 0;
        scoreEpreuve = 0;
        currentItem = 0;
        jsonStructureScript.chargeJsonStructure();
        newSystemeDeTraces.initialiseNewSystemeDeTraces();
        current_step = -1;
        resetItem();
    }

    private void resetItem()
    {
        gameObjFin.SetActive(false);
        StopAllCoroutines();
        if (list_choix_associed_with_prefabs != null)
        {
            foreach (groupemementChoixEtPrefabBoutonQCM gc in list_choix_associed_with_prefabs)
            {
                if (gc != null)
                {
                    if (gc.elementGDAssocied != null)
                    {
                        gc.elementGDAssocied.StopAllCoroutines();
                        Destroy(gc.elementGDAssocied.gameobj);
                    }
                    if (gc.elementDropZoneAssocied != null)
                    {
                        gc.elementDropZoneAssocied.StopAllCoroutines();
                        Destroy(gc.elementDropZoneAssocied.gameobj);
                    }
                    if (gc.boutonqcmAssocied != null)
                    {
                        gc.boutonqcmAssocied.StopAllCoroutines();
                        Destroy(gc.boutonqcmAssocied.gameobj);
                    }
                }
            }
        }

        epreuveitemscurrentSet = false;
        if (posScript.currentlyInstanciatedprefabImagePrincipale != null)
        {
            Destroy(posScript.currentlyInstanciatedprefabImagePrincipale.gameObject);
        }
        currentChoix = 0;
        scoreItem = 0;
        gdmanager.resetGDManager();
    }
    public ChargementJSONStructure.Asset returnA(string id)
    {
        if (jsonStructureScript.data.assets.ContainsKey(id))
        {
            return jsonStructureScript.data.assets[id];
        }
        else return null;
    }

    private ChargementJSONStructure.Asset checkAssetValidity(string id)
    {
        if (id != null && id.Length > 0)
        {
            ChargementJSONStructure.Asset a = returnA(id);
            if (a != null)
            {
                return a;
            }
        }
        return null;
    }

    public bool executeAsset(string id, Action mafonction, bool img=false, bool epreuveStep=false)
    {
        bool anAssetSoundExists = false;
        if(id!=null &&  id.Length>0)
        {
            ChargementJSONStructure.Asset a = returnA(id);
            if (a != null)
            {
                if (img && a.img_path != null && a.img_path.Length > 0)
                {
                    Sprite image = Resources.Load<Sprite>(a.img_path);
                    if (image != null)
                    {
                        if (epreuveStep)
                        {
                            posScript.SetImageEpreuve(image);

                        }
                        else
                        {
                            posScript.SetSpriteAndPosition(image);

                        }
                        anAssetSoundExists = true;
                    }
                }
                else if (!img && a.snd_path != null && a.snd_path.Length > 0)
                {
                    AudioClip aud = Resources.Load<AudioClip>(a.snd_path);
                    if (aud != null)
                    {
                        anAssetSoundExists = true;
                        playsoundCoroutine = StartCoroutine(replayButtonPlaySound(aud, mafonction));
                    }
                    else if (mafonction != null)
                    {
                        StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(mafonction));
                    }
                }
                else if (mafonction != null)
                {
                    StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(mafonction));
                }
            }
            else if (mafonction != null)
            {
                StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(mafonction));
            }
        }
        else if (mafonction != null)
        {
            StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(mafonction));
        }
        return anAssetSoundExists;
    }

    public void flecheReadyDisplayed()
    {
        if (posScript.currentlyInstanciatedprefabImagePrincipale != null)
        {
            playerTurn = true;

            // le son ready a bien �t� jou�, on attends que le joueur clic sur la fleche ready.

            posScript.currentlyInstanciatedprefabImagePrincipale.gameObject.SetActive(true);

        }
        else
        {
            flecheReadyBeenClicked(true);
        }
    }
    public void flecheReadyBeenClicked(bool fromcode = false)
    {
        if(fromcode || (!fromcode && !gameObjFin.activeSelf))
        {
            //Debug.Log("flecheReadyBeenClicked");
            playerTurn = false;
            playSteps();
        }

    }
    private bool epreuveitemscurrentSet = false;
    private List<EpreuveItem> epreuvesitemsCurrent;
    public void playSteps()
    {

        if (texteCheat.text.Length > 300)
        {
            texteCheat.text = texteCheat.text.Substring(150);
        }
        // boutonnext cheat
        if (boutonCheatNext)
        {
            if (playsoundCoroutine != null)
            {
                StopCoroutine(playsoundCoroutine);
            }
            boutonCheatNext = false;
        }

        s = jsonStructureScript.data.sessions[currentSession];
        e = s.epreuves[currentEpreuve];
        if (e.nbItemsMax == 0 && e.items != null)
        {
            e.nbItemsMax = e.items.Count;
        }
        int numsess = currentSession + 1;
        texteSessionQuestionNumero.text = "Session N°" + numsess.ToString() + "/" + jsonStructureScript.data.sessions.Count.ToString()+"\n";
        int numiteTotal = 0;
        int numIteCurrent = 1;
        int indexxeppr = 0;
        foreach (Epreuve eee in s.epreuves)
        {
            if(indexxeppr< currentEpreuve)
            {
                numIteCurrent += eee.items.Count;
            }
            else if (indexxeppr== currentEpreuve)
            {
                numIteCurrent += currentItem;
            }
            numiteTotal += eee.items.Count;
            indexxeppr++;
        }
        texteSessionQuestionNumero.text += "Question N°" + numIteCurrent.ToString() + "/" + numiteTotal.ToString();
        if (!epreuveitemscurrentSet)
        {
            epreuvesitemsCurrent = e.items;
            //int rand = UnityEngine.Random.Range(-1, 2);
            if (epreuvesitemsCurrent == null)
            {
                Debug.LogError("this item is null ");
                endItem();
            }
            else
            {
                if (e.randomiser){
                    epreuvesitemsCurrent = ShuffleList(epreuvesitemsCurrent);
                }
                epreuveitemscurrentSet = true;

            }


        }
        if (epreuvesitemsCurrent != null)
        {
            i = epreuvesitemsCurrent[currentItem];

            if (e.modalite == "GD")
            {
                gdmanager.playStepsGD();
            }
            else if (e.modalite == "QCM")
            {
                qcmmanager.playStepsQCM();
            }
        }

    }

    public List<EpreuveItem> ShuffleList(List<EpreuveItem> list)
    {
        List<EpreuveItem> temp = new List<EpreuveItem>();
        List<EpreuveItem> shuffled = new List<EpreuveItem>();
        temp.AddRange(list);

        for (int i = 0; i < list.Count; i++)
        {
            int index = UnityEngine.Random.Range(0, temp.Count);
            shuffled.Add(temp[index]);
            temp.RemoveAt(index);
        }

        return shuffled;
    }

    public List<groupemementChoixEtPrefabBoutonQCM> ShuffleItems(List<groupemementChoixEtPrefabBoutonQCM> list)
    {
        List<groupemementChoixEtPrefabBoutonQCM> temp = new List<groupemementChoixEtPrefabBoutonQCM>();
        List<groupemementChoixEtPrefabBoutonQCM> shuffled = new List<groupemementChoixEtPrefabBoutonQCM>();
        temp.AddRange(list);

        for (int i = 0; i < list.Count; i++)
        {
            int index = UnityEngine.Random.Range(0, temp.Count);
            shuffled.Add(temp[index]);
            temp.RemoveAt(index);
        }

        return shuffled;
    }

    private bool initialisationFirstEpreuve_EnCours = false;
    public void nextEpreuve(bool initialisation=false)
    {
        if (initialisation)
        {
            s = jsonStructureScript.data.sessions[currentSession];
            currentEpreuve = -1;
            initialisationFirstEpreuve_EnCours = true;
        }

        //Debug.Log("s = " + s + " currentEpreuve=" + currentEpreuve);
        // on regarde s'il y a une autre epreuve dans la meme session a lancer
        if (s!=null && currentEpreuve >= s.epreuves.Count - 1)
        {
            if (initialisationFirstEpreuve_EnCours)
            {
                // il n'y a aucune epreuve de valide dans cette session on regarde si il y a une session suivante
                currentSession++;
                if(currentSession>= jsonStructureScript.data.sessions.Count)
                {
                    // Dernière session atteinte. Fin du jeu
                    Debug.Log("Dernière session atteinte. Fin du jeu");
                    ouvrirMenu(true);
                }
                else
                {
                    //on initialise la session suivante existante sur sa premiere epreuve, sans passer par une deconnexion
                    nextEpreuve(true);
                }
            }
            else
            {
                ouvrirMenu(true);
            }
            //pas d'autre epreuve dans cette session, on clot la session
            //Debug.Log("pas d'autre epreuve dans cette session, on clot la session currentEpreuve="+ currentEpreuve+ " s.epreuves.Count="+ s.epreuves.Count);
        }
        else
        {
            Debug.Log("il y a une autre epreuve dans cette session, on voit si on la lance");
            currentEpreuve++;
            if (playableEpreuve(s.epreuves[currentEpreuve]))
            {
                currentItem = 0;
                epreuveConsignebeenPlayed = false;
                current_step = -1;
                initialisationFirstEpreuve_EnCours = false;
                resetItem();
                playSteps();
            }
            else
            {
                Debug.Log("next epreuve from next epreuve");
                nextEpreuve();
            }
        }
    }

    public bool playableEpreuve(Epreuve test_ep)
    {
        Debug.Log("testing playableEpreuve id="+test_ep.id+" titre ="+test_ep.titre);
        bool epreuveIsPlayable = true;
        DateTime dateNow = DateTime.Now;
        DateTime dateTime;
        if (test_ep!=null && test_ep.debut!=null && test_ep.debut.Length > 0)
        {
            if (DateTime.TryParse(test_ep.debut, out dateTime))
            {
                if(dateTime > dateNow)
                {
                    Debug.Log("dateTime debut ="+ dateTime+" exceeds dateNow="+ dateNow);
                    epreuveIsPlayable = false;
                }
            }
            else
            {
                Debug.Log("debut value does not match a valid date");

            }
        }
        else
        {
            Debug.Log("this epreuve does not have a debut value");
        }
        if (test_ep != null && test_ep.fin != null && test_ep.fin.Length > 0)
        {
            if (DateTime.TryParse(test_ep.fin, out dateTime))
            {
                if (dateTime < dateNow)
                {
                    epreuveIsPlayable = false;
                    Debug.Log("dateTime fin =" + dateTime + " bellow dateNow=" + dateNow);

                }
            }
            else
            {
                Debug.Log("end value does not match a valid date");

            }
        }
        else
        {
            Debug.Log("this epreuve does not have an end value");

        }
        Debug.Log("epreuveIsPlayable="+ epreuveIsPlayable);

        return epreuveIsPlayable;
    }



    public void endItem()
    {
        Debug.Log("endItem");
        if (posScript.currentlyInstanciatedImageEpreuveCentered != null)
        {
            Destroy(posScript.currentlyInstanciatedImageEpreuveCentered.gameObject);
        }
        Resources.UnloadUnusedAssets();
        if (epreuvesitemsCurrent == null || (epreuvesitemsCurrent!=null && currentItem >= epreuvesitemsCurrent.Count - 1) ||(e!=null && currentItem>=e.nbItemsMax-1) )
        {
            Debug.Log("pas d'autre item dans cette epreuve currentItem=" + currentItem + " epreuvesitemsCurrent.Count= " + epreuvesitemsCurrent.Count);
            // pas d'autre liste d'items dans cette epreuve
            nextEpreuve();
            //s.epreuves[currentEpreuve];
        }
        else
        {
            // il y a une autre liste d'items dans cette epreuve, on la charge
            Debug.LogError("reinit with new item");
            currentItem++;
            i = epreuvesitemsCurrent[currentItem];
            //Debug.Log("i=" + i+ " currentItem="+ currentItem+ " current_step="+ current_step);
            current_step = -1;
            resetItem();
            playSteps();
        }
    }
    private float actionUtilisateurStartTimeItem_Reveil;
    private bool reveilEnCours = false;
    public void playerturnnow()
    {
        playerTurn = true;
        if(current_step >= 5)
        {
            actionUtilisateurStartTimeItem_Reveil = actionUtilisateurStartTimeItem = Time.time;
            //texteCheat.text += "/GOPLAY";
        }
        else
        {
            //texteCheat.text += "/GOINTERACT";
        }

    }
    private void Update()
    {
        if((mainAudioSource!=null && mainAudioSource.isPlaying && !playerTurn ) || (!playerTurn && !gameObjFin.activeSelf))
        {
            fondNoirImage.SetActive(true);
        }
        else
        {
            fondNoirImage.SetActive(false);

        }

        if (playerTurn && current_step >= 5 && !reveilEnCours)
        {
            if ((Time.time - actionUtilisateurStartTimeItem_Reveil > 10.0f && i.type == "tuto") || (Time.time - actionUtilisateurStartTimeItem_Reveil > 20.0f))
            {
                reveilEnCours = true;
                executeAsset(i.reveil, reveilDone, false);

            // reveil
            }
        }
        if (bannissementIsOn)
        {
            DateTime now = DateTime.Now;

            // Vérifie si la date actuelle est antérieure à la date d'expiration
            if (now < bannissementExpirationDateTime)
            {
                // Calcule la durée restante jusqu'à la reprise
                TimeSpan tempsRestant = bannissementExpirationDateTime - now;

                // Affiche le temps restant
                BoutonsessionActuelleTexte.text = "Utilisateur en pause. Reprise possible dans "+ tempsRestant.Minutes + " minutes et "+ tempsRestant.Seconds + " secondes";
            }
            else
            {
                BoutonsessionActuelleTexte.text = "Pause terminée. Lancer la session";
                boutonDeconnexion.SetActive(false);
                bannissementIsOn = false;
                bannissementIsOver = true;
                Debug.Log("La pause a déjà expiré.");
            }

        }
    }

    private void reveilDone()
    {
        Debug.Log("reveil done");
        reveilEnCours = false;
        actionUtilisateurStartTimeItem_Reveil = Time.time;
    }

    public void boutonCheatNextClickedNow()
    {
        // action
        if (boutonCheatNextImage.color == Color.white)
        {
            boutonCheatNext = true;
            texteCheat.gameObject.SetActive(true);
        }

        // unlockage
        if (!OnGoingTapToUnlockCheat && boutonCheatNextImage.color!=Color.white)
        {
            // premier clic, on lance le timer
            StartCoroutine(compteurUnlockCheat());
        }
        else if (boutonCheatNextImage.color != Color.white)
        {
            // deuxieme clic et troiseme clic
            compteurclickcoinDroitHautToUnlockCheat++;
            if (compteurclickcoinDroitHautToUnlockCheat >= 5) //au troisieme clic
            {
                boutonCheatNextImage.color = Color.white; // on rend visible le bouton cheat
            }
        }
    }
    private IEnumerator compteurUnlockCheat()
    {
        OnGoingTapToUnlockCheat = true;
        float timecumule = 0.0f;
        while (true)
        {
            timecumule += Time.deltaTime;
            if (timecumule > 2.0f)
            {
                compteurclickcoinDroitHautToUnlockCheat = 0;
                break;
            }
            yield return null;
        }
        OnGoingTapToUnlockCheat = false;
    }
    private bool audioIsPaused = false;
    private IEnumerator replayButtonPlaySound(AudioClip unCLipSound, Action mafonction)
    {

        mainAudioSource.Stop();
        mainAudioSource.clip = unCLipSound;
        mainAudioSource.Play();

        while (audioIsPaused || (!boutonCheatNext && mainAudioSource.isPlaying))
        {

            if (Time.timeScale != 0)
            {
                // Si le Time.timeScale n'est pas zéro et que l'AudioSource est en pause, le reprendre
                if (audioIsPaused)
                {
                    mainAudioSource.UnPause();
                    audioIsPaused = false;
                }
            }
            yield return null;
        }
        if (!boutonCheatNext)
        {
            yield return new WaitForSeconds(0.5f);
        }
        mafonction();
    }

    public void instancieAllChoixAtOnce()
    {
        int choixNow = 0;
        foreach (groupemementChoixEtPrefabBoutonQCM g in list_choix_associed_with_prefabs)
        {
            groupemementChoixEtPrefabBoutonQCM groupe = list_choix_associed_with_prefabs[choixNow];
            GameObject ggg = posScript.placeImages(choixNow, g.choix);
            if (e.modalite == "GD")
            {
                groupe.boutonqcmAssocied = groupe.elementGDAssocied = ggg.GetComponent<elementGD>();
            }
            else
            {
                boutonQCM b = ggg.GetComponent<boutonQCM>();
                list_choix_associed_with_prefabs[choixNow].boutonqcmAssocied = b;
            }
            choixNow++;
        }
    }

    public void makeEachChoiceClignoteOneAfterTheOther()
    {
        //Debug.Log("makeEachChoiceClignoteOneAfterTheOther");
        if (currentChoix > 0)
        {
            list_choix_associed_with_prefabs[currentChoix - 1].boutonqcmAssocied.stopClignote();
        }

        if (currentChoix >= list_choix_associed_with_prefabs.Count)
        {
            //Debug.Log("all choix were read");
            currentChoix = 0;
            playSteps();
        }
        else
        {
            groupemementChoixEtPrefabBoutonQCM groupe = list_choix_associed_with_prefabs[currentChoix];
            currentChoix++;
            if (e.modalite == "QCM")
            {
                if (i.surligner)
                {
                    groupe.boutonqcmAssocied.clignote();
                }
                if (i.enumerer)
                {
                    if (currentChoix == (list_choix_associed_with_prefabs.Count))
                    {
                        dernierChoixAudioclip = groupe.choix.son;
                        executeAsset(i.separateurChoix, lireDernierChoixWhenAllAreInstanciated, false);
                    }
                    else
                    {
                        executeAsset(groupe.choix.son, makeEachChoiceClignoteOneAfterTheOther, false);
                    }

                }
                else
                {
                    StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(makeEachChoiceClignoteOneAfterTheOther));
                }

            }
            else
            {
                StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(makeEachChoiceClignoteOneAfterTheOther));
            }

        }
    }


    public void instancieAndPlayCHoix()
    {
        if (currentChoix > 0)
        {
            list_choix_associed_with_prefabs[currentChoix - 1].boutonqcmAssocied.stopClignote();
        }

        if (currentChoix >= list_choix_associed_with_prefabs.Count)
        {
            Debug.Log("all choix were read");
            currentChoix = 0;
            playSteps();
        }
        else
        {
            groupemementChoixEtPrefabBoutonQCM groupe = list_choix_associed_with_prefabs[currentChoix];
            GameObject ggg = posScript.placeImages(currentChoix, groupe.choix);
            if (e.modalite == "GD")
            {
               groupe.boutonqcmAssocied = groupe.elementGDAssocied = ggg.GetComponent<elementGD>();
            }
            else
            {
                boutonQCM b = ggg.GetComponent<boutonQCM>();
                list_choix_associed_with_prefabs[currentChoix].boutonqcmAssocied = b;
            }

            currentChoix++;
            if (e.modalite == "QCM")
            {
                if (i.surligner)
                {
                    groupe.boutonqcmAssocied.clignote();
                }
                if (i.enumerer)
                {
                    if (currentChoix == (list_choix_associed_with_prefabs.Count))
                    {
                        dernierChoixAudioclip = groupe.choix.son;
                        executeAsset(i.separateurChoix, lireDernierChoix, false);
                    }
                    else
                    {
                        executeAsset(groupe.choix.son, instancieAndPlayCHoix, false);
                    }

                }
                else
                {
                    StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(instancieAndPlayCHoix));
                }

            }
            else
            {
                StartCoroutine(justWaitOneFrameBeforeLaunchingFunction(instancieAndPlayCHoix));
            }

        }
    }
    private void lireDernierChoix()
    {
        executeAsset(dernierChoixAudioclip, instancieAndPlayCHoix,false);
    }

    private void lireDernierChoixWhenAllAreInstanciated()
    {
        executeAsset(dernierChoixAudioclip, makeEachChoiceClignoteOneAfterTheOther, false);
    }
    private IEnumerator justWaitOneFrameBeforeLaunchingFunction(Action uneFonction)
    {
        yield return new WaitForEndOfFrame();
        uneFonction();
    }
    public TextMeshProUGUI texteFinSession;
    public GameObject gameObjFin;
    public GameObject boutonSessionSuivante;
    public GameObject boutonSessionEnCours;
    public GameObject boutonDeconnexion;
    public TextMeshProUGUI BoutonsessionActuelleTexte;
    public TextMeshProUGUI BoutonnextsessionTexte;
    public TextMeshProUGUI infoSessionItemEnCours;
    private bool toutessessionsacheves;

    public void ouvrirMenu (bool findesession=false)
    {
        Debug.Log("ouvrirMenu");
        boutonDeconnexion.SetActive(false);
        boutonSessionSuivante.SetActive(false);
        compteurdeclickOnBoutonRAZ = 0;
        boutonDeconnexionText.text = "Déconnecter l'utilisateur";
        deconnexionPlusRAZ = false;

        int sessionActuelle = currentSession + 1;
        BoutonsessionActuelleTexte.text = "Retour session en cours " + sessionActuelle.ToString() + "/" + jsonStructureScript.data.sessions.Count.ToString();
        infoSessionItemEnCours.text = "Session\nN°" + sessionActuelle.ToString() + "/" + jsonStructureScript.data.sessions.Count.ToString();

        int nbItemsPasses = 0;
        bool nbitempassesReached = false;
        int nbItemsTotauxDansCetteSession = 0;

        int indexepreuveParsed = 0;
        foreach (Epreuve epp in s.epreuves)
        {
            int indexItemParsed = 0;
            foreach (EpreuveItem eii in epp.items)
            {
                if (!nbitempassesReached)
                {
                    nbItemsPasses++;
                }
                nbItemsTotauxDansCetteSession++;
                if (indexepreuveParsed > currentEpreuve || (indexepreuveParsed >= currentEpreuve && indexItemParsed >= currentItem))
                {
                    nbitempassesReached = true;
                }
                indexItemParsed++;
            }
            indexepreuveParsed++;
        }
        int maxsession = jsonStructureScript.data.sessions.Count - 1;
        int maxepreuve = jsonStructureScript.data.sessions[maxsession].epreuves.Count - 1;
        int maxitem = jsonStructureScript.data.sessions[maxsession].epreuves[maxepreuve].items.Count - 1;


        Debug.Log("nbItemsPasses = " + nbItemsPasses + " nbItemsTotauxDansCetteSession=" + nbItemsTotauxDansCetteSession + " i.id=" + i.id + " e.id=" + e.id);
        infoSessionItemEnCours.text += "\n\nQuestion\nN°" + nbItemsPasses.ToString() + "/" + nbItemsTotauxDansCetteSession.ToString();
        if (i == jsonStructureScript.data.sessions[maxsession].epreuves[maxepreuve].items[maxitem])
        {
            infoSessionItemEnCours.text += "\n\nFIN d'EVALULU";
        }
        else if (findesession)
        {
            infoSessionItemEnCours.text += "\n\nFIN de session N°"+sessionActuelle.ToString() + "/" + jsonStructureScript.data.sessions.Count.ToString();
        }

        if (findesession)
        {
            boutonSessionEnCours.SetActive(false);
        }
        else
        {

            boutonSessionEnCours.SetActive(true);
        }
        gameObjFin.SetActive(true);


        if (findesession)
        {
            int futuresession = currentSession + 1;
            gestionProg.SauveProgression(futuresession);
            texteFinSession.text = "Fin de session. Envoi des traces au serveur en cours...";
            newSystemeDeTraces.sendThisUserTracesToHMPlugin(true);
        }
        else
        {
            Time.timeScale = 0.0f;
            audioIsPaused = true;
            mainAudioSource.Pause();
            if (!toutessessionsacheves)
            {
                newSystemeDeTraces.sendThisUserTracesToHMPlugin(false);

            }
            else
            {
                boutonSessionEnCours.SetActive(false);
                boutonDeconnexion.SetActive(true);
            }
            if (bannissementIsOn)
            {
                boutonDeconnexion.SetActive(true);

            }
        }


    }
    public void clicRetourSessionEnCOurs()
    {
        if (!bannissementIsOn)
        {
            Time.timeScale = 1.0f;
            Debug.Log("clicRetourSessionEnCOurs");
            gameObjFin.SetActive(false);
            if (bannissementIsOver)
            {
                bannissementIsOver = false;
                nextEpreuve(true);

            }
        }
    }

    public void clicSessionSuivante()
    {
        if (bannissementIsOn)
        {
            bannissementIsOn = false;
            string AttributBannissement = "bannissement_" + NewSystemeDeTraces.returnUserIDFLuence_or_UserIDHM();
            if (PlayerPrefs.HasKey(AttributBannissement))
            {
                PlayerPrefs.SetString(AttributBannissement, "");
                PlayerPrefs.Save();
            }
            boutonSessionSuivante.SetActive(false);
            Time.timeScale = 1.0f;
            nextEpreuve(true);
        }
        /*
        Debug.Log("clicSessionSuivante");
        resetItem();
        currentItem = 0;
        currentEpreuve=0;
        currentSession++;
        gestionProg.SauveProgression(currentSession);
        scoreSession = 0;
        sessionConsignebeenPlayed = false;
        epreuveConsignebeenPlayed = false;
        current_step = -1;
        playerTurn = false;
        playSteps();
        gameObjFin.SetActive(false);*/

    }
    private bool deconnexionViaClickBoutonDeconnexion;
    public void deconnexion()
    {
        Debug.Log("deconnexion");
        //gestionProg.SauveProgression(currentSession);
        //newSystemeDeTraces.sendThisUserTracesToHMPlugin(true);
        boutonSessionSuivante.SetActive(false);
        boutonSessionEnCours.SetActive(false);
        boutonDeconnexion.SetActive(false);
        deconnexionViaClickBoutonDeconnexion = true;
        StartCoroutine(terminateScene());
        //texteFinSession.text = "FIN DE SESSION / Envoi des traces au serveur en cours...";
    }

    public void launchTerminateScene()
    {
        deconnexionViaClickBoutonDeconnexion = false;
        StartCoroutine(terminateScene());
    }
    public IEnumerator terminateScene()
    {
        Debug.Log("terminateScene deconnexionPlusRAZ="+ deconnexionPlusRAZ);
        if (deconnexionPlusRAZ)
        {
            gestionProg.SauveProgression(0, true);
        }
        else if (!deconnexionViaClickBoutonDeconnexion)
        {
            // on enregistre dans les playerprefs une ref à ce userlogin+teachercode+timestamp à la minuté près pour le bannir
            string AttributBannissement = "bannissement_" + NewSystemeDeTraces.returnUserIDFLuence_or_UserIDHM();
            DateTime currentTime = DateTime.Now;
            string timestampString = currentTime.ToString("yyyy-MM-dd HH:mm");
            PlayerPrefs.SetString(AttributBannissement, timestampString);
            PlayerPrefs.Save();
            // Sauvegarde des modifica
        }
        Time.timeScale = 1.0f;
        Debug.Log("terminateScene");
        texteFinSession.text = "Deconnexion en cours";
        yield return new WaitForSecondsRealtime(1.5f);
        SceneManager.LoadScene("Scenes/SplashScreen");
    }

}