using GhostSystem;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
using System.Collections.Generic;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
using System.Threading.Tasks;

public class FlushAndLoad : MonoBehaviour
{
    public TMP_Text output;
    public TMP_Text instruction;
    public GhostRecorderBatch recorder;
    public GameObject loadingScreen;
    public GameObject canvas;
    public GameObject passthroughLayer;

    private string sceneId;

    private void OnEnable()
    {
        GhostRecorderBatch.OnUploadFinished += HandleUploadFinished;
        RoomManager.OnSceneIdReady += HandleSceneIdReady;
    }

    private void OnDisable()
    {
        GhostRecorderBatch.OnUploadFinished -= HandleUploadFinished;
        RoomManager.OnSceneIdReady -= HandleSceneIdReady;
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger))
        {
            if (sceneId == "End") Application.Quit();
            else
            {
                output.text = "Flush...";
                _ = LoadScene();
                /*loadingScreen.SetActive(true);
                canvas.SetActive(false);

                recorder.Flush();
                GetComponent<SceneLoader>().NewRoom();*/
            }
            
        }
    }

    private void HandleUploadFinished()
    {
        loadingScreen.SetActive(false);
        output.text = "";
        if (sceneId == "End")
        {
            output.text = "Durchlauf beendet.";
        }
    }

    private void HandleSceneIdReady(string id, List<GameObject> doors)
    {
        sceneId = id;
        if (id == "Room1")
        {
            loadingScreen.SetActive(false);
            passthroughLayer.SetActive(false);
        }
        if (id == "End")
        {
            instruction.text = "Drücke den rechten Trigger, um die Anwendung zu beenden.";
            canvas.SetActive(true);
            passthroughLayer.SetActive(true);
        }
    }

    private async UniTask Loadingscreen()
    {
        loadingScreen.SetActive(true);
        canvas.SetActive(false);
    }

    private async UniTaskVoid LoadScene()
    {
        await Loadingscreen();
        recorder.Flush();
        GetComponent<SceneLoader>().NewRoom();
    }
}
