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

public class UIManager : MonoBehaviour
{
    public static UIManager Instance;

    public MeshRenderer[] jumpLights;
    public GameObject[] jumpLightsLights;
    public TMPro.TextMeshProUGUI remainingJumpsLabel;

    public Transform credits;


    float lightBlinkTimer;
    bool isLightOn;
    bool rollCredits;

    const float lightBlinkDuration = 0.8f;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        remainingJumpsLabel.text = "Remaining jumps: " + StoryManager.Instance.RemainingJumpsAmount.ToString();

        GameEventManager.OnJumpEnd += OnJumpEnd;

        credits.localPosition = new Vector3(0, 0, 20);
    }

    void Update()
    {
        if(lightBlinkTimer > 0)
        {
            lightBlinkTimer -= Time.deltaTime;
            if(lightBlinkTimer <= 0)
            {
                lightBlinkTimer = lightBlinkDuration;
                isLightOn = !isLightOn;
                LightJumpLights(isLightOn);
            }
        }

        if(rollCredits)
        {
            credits.localPosition = credits.localPosition + new Vector3(0, Time.deltaTime * 100, 0);
            if(credits.localPosition.y >= 1200)
                rollCredits = false;
        }
    }

    public void ActivateJumpButton(bool activate)
    {
        //jumpButton.interactable = activate;
        isLightOn = activate;
        lightBlinkTimer = activate ? lightBlinkDuration : -1f;
        LightJumpLights(activate);
    }

    void LightJumpLights(bool light)
    {
        for(int i = 0; i < jumpLights.Length; i++)
        {
            jumpLights[i].material = light ? GameUtils.Instance.lightGreenMaterial : 
                lightBlinkTimer > 0 ? GameUtils.Instance.lightOffMaterial : GameUtils.Instance.lightRedMaterial;
            jumpLightsLights[i].SetActive(light);
        }
        if(light)
        {
            StoryManager.Instance.OnJumpLightOn();
        }
    }

    public void OnJumpButton()
    {
        ActivateJumpButton(false);
        if(MapParametersManager.Instance.AreAllParametersCorrect() && StoryManager.Instance.RemainingJumpsAmount > 0)
        {
            StoryManager.Instance.HyperspaceJump();

            if(StoryManager.Instance.RemainingJumpsAmount > 0)
            {
                remainingJumpsLabel.text = "Remaining jumps: " + StoryManager.Instance.RemainingJumpsAmount.ToString();
            }
            else
            {
                remainingJumpsLabel.text = "DESTINATION REACHED";
            }
        }
    }

    void OnJumpEnd()
    {
        if(StoryManager.Instance.RemainingJumpsAmount == 0)
        {
            rollCredits = true;
        }
    }
}

