﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

public class reponse_text : MonoBehaviour
{
    private TMPro.TMP_InputField reponset;
    [SerializeField] private TMPro.TMP_Text tmp_question;
    [SerializeField] private GameObject CanvasFilePrefabs;
    private gestionfichier canvasFile;
    private Button enregistreT;
    private string Reponse_fichier;
    [Header("titre de la question:")]
    public string questionName = "";
    [Header("donnez la réponse")]
    [SerializeField] string reponseouverte = "";


    gestionfichier myGestionFichier;

    // Start is called before the first frame update
    void Start()
    {
        myGestionFichier = FindObjectOfType<gestionfichier>();
        enregistreT = GetComponentInChildren<Button>();
        Debug.Log(enregistreT);
        reponset = GetComponentInChildren<TMPro.TMP_InputField>();
        Debug.Log(reponset);
        enregistreT.onClick.AddListener(Sauvegarde_text);
        tmp_question.text = questionName;
    }


    public void SetQuestionTitle()
    {
        tmp_question.text = questionName;
    }

    void Sauvegarde_text()
    {
        Reponse_fichier = this.questionName + ";" + reponset.text + "\n";

        File.AppendAllText(myGestionFichier.chemin, Reponse_fichier);

        enregistreT.gameObject.SetActive(false);
        enregistreT.onClick.RemoveListener(Sauvegarde_text);
    }

    public void CreateSaveFile()
    {
        if (canvasFile == null)
            canvasFile = FindObjectOfType<gestionfichier>();

        if (CanvasFilePrefabs != null && canvasFile == null)
        {
            canvasFile = Instantiate(CanvasFilePrefabs).GetComponent<gestionfichier>();
            this.GetComponent<MCQ_AnswerManager>().SetFile = canvasFile.GetComponent<gestionfichier>();
        }
        else
        {
            //Debug.LogError("Error in : " + this.transform.name + " Calling CreateSaveFile function the prefabs is null, make sure you put it correctly in the editor");
        }
    }

    public void Exportmoodle()
    {
        int index = 1;
        string path = Application.streamingAssetsPath + "/" + "questionouverte_ExportMoodle" + index + ".txt";

        while (File.Exists(path))
        {
            index++;
            path = Application.streamingAssetsPath + "/" + "questionouverte_ExportMoodle" + index + ".txt";
        }
        string quest = questionName + "{=" + reponseouverte + "}";
        File.WriteAllText(path, quest);

    }
}
