﻿using DEC.Unity.XR;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class MCQ_Generator : MonoBehaviour
{

    [SerializeField] private GameObject MCQ_InteractiveCanvasPrefabs = default;
    [SerializeField] private GameObject MCQ_AnswerPrefab = default;
    [SerializeField] private GameObject CanvasFilePrefabs;
    [SerializeField] private TMPro.TMP_Text QuestionTitre;

    GameObject contentParent = default;
    Canvas MCQ_Canvas = default;
    List<MCQ_Answer> addedCanvas = new List<MCQ_Answer>();

    [Header("Ecrivez le titre de la question : ")]
    public string question = "Oui";



    private gestionfichier canvasFile = default;
    //public GameObject GetCanvasPrefabs { get { return MCQ_InteractiveCanvasPrefabs; } }

    private void Start()
    {
        Debug.Log("question titre : " + question);
        QuestionTitre.text = question;
    }

    public void SetUpAddedCanvas()
    {
        if (addedCanvas.Count == 0)
        {
            addedCanvas = new List<MCQ_Answer>(contentParent.GetComponentsInChildren<MCQ_Answer>());
        }
    }

    public void CreateCanvasAndSetContentParent()
    {
        MCQ_Canvas = this.GetComponentInChildren<Canvas>();
        if (MCQ_Canvas == null)
        {
            Instantiate(MCQ_InteractiveCanvasPrefabs, this.transform);
            CreateCanvasAndSetContentParent();
        }
        SetContentParent();
    }

    public void ChangeQuestionValue()
    {
        QuestionTitre.text = question;

    }

    private void SetContentParent()
    {
        contentParent = MCQ_Canvas.GetComponentInChildren<AnswerParent>().gameObject;
    }

    public void CreateAnswer(string _answerValue, string _name, bool _isRightAnswer)
    {
        if (contentParent == null)
            SetContentParent();
        if (MCQ_InteractiveCanvasPrefabs == null)
        {
            Debug.LogError("Error in : " + this.transform.name + "  the canvas prefabs is null, make sure you put it correctly in the editor");
        }
        else
        {
            if (MCQ_AnswerPrefab != null)
            {
                GameObject answer = Instantiate(MCQ_AnswerPrefab, contentParent.transform);
                answer.name = _name;
                answer.GetComponent<MCQ_Answer>().SetUpParameters(_answerValue, _isRightAnswer);
                addedCanvas.Add(answer.GetComponent<MCQ_Answer>());
                Debug.Log("answer created : " + answer);
            }
            else
            {
                Debug.LogError("Error in : " + this.transform.name + " Calling CreateAnserFunction the answer prefabs is null, make sure you put it correctly in the editor");
            }
        }
    }

    [ContextMenu("Debug list")]
    public void UpdateAnswers()
    {
        if (addedCanvas.Count > 0)
        {
            for (int i = addedCanvas.Count - 1; i >= 0; i--)
            {
                if (addedCanvas[i] == null)
                {
                    addedCanvas.Remove(addedCanvas[i]);
                    Debug.Log("Remove null answers");
                }
                else
                {
                    Debug.Log("answer is not null " + addedCanvas[i].gameObject.name);
                }
            }
        }
        else
        {
            MCQ_Answer[] foundAnswer = contentParent.GetComponentsInChildren<MCQ_Answer>();
            for (int i = 0; i < foundAnswer.Length; i++)
            {
                if (addedCanvas.Contains(foundAnswer[i]) == false)
                    addedCanvas.Add(foundAnswer[i]);
            }
        }
    }

    public void DeleteLastAnswer()
    {
        if (addedCanvas.Count > 0)
        {
            for (int i = addedCanvas.Count - 1; i > 0; i--)
            {
                if (addedCanvas[i] == null)
                    addedCanvas.Remove(addedCanvas[i]);
            }
            GameObject elementToDestroy = addedCanvas[addedCanvas.Count - 1].gameObject;
            addedCanvas.Remove(addedCanvas[addedCanvas.Count - 1]);
            DestroyImmediate(elementToDestroy);
        }
    }

    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 ExportDataInCSVFile()
    {
        int index = 1;
        string path = Application.streamingAssetsPath + "/" + "QCM_ExportMoodle" + index + ".txt";

        while (File.Exists(path))
        {
            index++;
            path = Application.streamingAssetsPath + "/" + "QCM_ExportMoodle" + index + ".txt";
        }

        string answers = "";
        for (int i = 0; i < addedCanvas.Count; i++)
        {
            if (addedCanvas[i].GetAnswerValue != "")
            {
                answers += (addedCanvas[i].IsRightAnswer) ? "=" : "~";
                answers += addedCanvas[i].GetAnswerValue;
                answers += " ";
            }
        }
        string tmpStr = question + "{" + answers + "}";
        tmpStr.Replace("/n", "");
        File.WriteAllText(path, tmpStr);

    }
}
