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

public class PromptManager : MonoBehaviour
{
    [SerializeField] private Text help;
    [SerializeField] private Text warn;
    [SerializeField] private float lingerDuration = 5;
    [SerializeField] private float fadeDuration = 5;

    private Coroutine helpCoroutine;
    private Coroutine warnCoroutine;

    private void Start()
    {
        GameManager.PromptManager = this;
        help.color = new Color(help.color.r, help.color.g, help.color.b, 0);
        warn.color = new Color(warn.color.r, warn.color.g, warn.color.b, 0);
        //StartCoroutine(Tester());
    }

    public void Landing()
    {
        HelpPrompt("Landing!");
    }

    public void Landed()
	{
        HelpPrompt("Build and harvest the flesh of our enemies!");
	}

    public void Win()
	{
        HelpPrompt("You have survived. You may Quit.");
	}

    public void Full()
	{
        HelpPrompt("We have enough resources. Launch!");
	}

    public void Launch()
    {
        HelpPrompt("We're blasting off again!");
    }

    public void Lose()
	{
        WarnPrompt("You have died. Reset.");
	}

    public void MoreGas()
    {
        WarnPrompt("You need to harvest more resources.");
    }

    /*
    private IEnumerator Tester()
	{
        float timer = lingerDuration + fadeDuration + 5;
        int count = 0;

        while (timer > 0)
		{
            HelpPrompt("Count: " + count);
            WarnPrompt("Count: " + count);
            yield return new WaitForSeconds(timer);
            count++;
            timer /= 2;
		}
	}
    */

    private void HelpPrompt(string promptText)
	{
        if (helpCoroutine != null)
        {
            StopCoroutine(helpCoroutine);
        }
        helpCoroutine = StartCoroutine(DisplayPrompt(help, promptText));
	}

    private void WarnPrompt(string promptText)
    {
        if (warnCoroutine != null)
        {
            StopCoroutine(warnCoroutine);
        }
        warnCoroutine = StartCoroutine(DisplayPrompt(warn, promptText));
    }

    private IEnumerator DisplayPrompt(Text textUI, string promptText)
	{
        textUI.text = promptText;
        textUI.color = textUI.color = new Color(textUI.color.r, textUI.color.g, textUI.color.b, 1);
        float fadeDuration = this.fadeDuration;

        yield return new WaitForSeconds(lingerDuration);

        while (fadeDuration > 0)
		{
            fadeDuration -= Time.deltaTime;
            float alpha = fadeDuration / this.fadeDuration;

            textUI.color = textUI.color = new Color(textUI.color.r, textUI.color.g, textUI.color.b, alpha);
            yield return null;
		}

        textUI.color = textUI.color = new Color(textUI.color.r, textUI.color.g, textUI.color.b, 0);
    }
}
