using System.Collections;
using System.Collections.Generic;
using Coherence.Toolkit;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using static WaveSystem;

public class WaveSystemHUD : MonoBehaviour
{
    public TextMeshProUGUI enemiesRemainingText;
    public TextMeshProUGUI waveNumberText;
    public TextMeshProUGUI timeRemainingText;

    public GameObject timeRemainingContainer;
    public GameObject youWonContainer;

    int prevEnemiesRemaining = -1;
    int prevWaveIndex = -1;

    bool didWin = false;

    void Start()
    {
        youWonContainer.SetActive(false);
    }

    void Update()
    {
        if (WaveSystem.Instance == null) return;

        int enemiesRemaining = WaveSystem.Instance.CurrentEnemiesRemaining();
        if (enemiesRemaining != prevEnemiesRemaining) {
            prevEnemiesRemaining = enemiesRemaining;
            enemiesRemainingText.text = enemiesRemaining.ToString();
            if (enemiesRemaining == 0 && WaveSystem.Instance.CurrentWaveIndex() == WaveSystem.Instance.TotalWaves() - 1) {
                if (didWin == false) {
                    didWin = true;
                    StartCoroutine(WinRoutine());
                }
                youWonContainer.SetActive(true);
            } else {
                youWonContainer.SetActive(false);
            }
        }
        if (WaveSystem.Instance.CurrentWaveIndex() != prevWaveIndex) {
            prevWaveIndex = WaveSystem.Instance.CurrentWaveIndex();
            waveNumberText.text = "Wave " + (WaveSystem.Instance.CurrentWaveIndex() + 1).ToString() + "/" + WaveSystem.Instance.TotalWaves().ToString();
        }

        float timeRemaining = WaveSystem.Instance.TimeRemainingInWave();
        if (timeRemaining > 0f) {
            timeRemainingContainer.SetActive(true);
            timeRemainingText.text = timeRemaining.ToString("0.0");
        } else {
            timeRemainingContainer.SetActive(false);
        }
    }

    IEnumerator WinRoutine() {
        yield return new WaitForSeconds(10f);
        CoherenceBridge bridge;
        if (CoherenceBridgeStore.TryGetBridge(gameObject.scene, out bridge)) {
            bridge.Disconnect();
        }
        youWonContainer.SetActive(false);
        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.None;
        CoherenceBridgeStore.MasterBridge.Disconnect();
        Destroy(CoherenceBridgeStore.MasterBridge.gameObject);
        SceneManager.LoadScene(0);
    }
}


