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

public class MainMenuUI : MonoBehaviour
{
    [Header( "Timing" )]
    [SerializeField]
    private float _fadeTime;
    
    [Header("References")]
    [SerializeField]
    private SceneLoader _loader;
    
    [SerializeField]
    private CanvasGroup _navigation;

    private CanvasGroup _current;

    private void Awake()
    {
        ShowMenu( _navigation );
    }

    public void StartGame()
    {
        _loader.LoadScene( SceneType.Gameplay );
    }

    public void ShowMenu(CanvasGroup newMenu)
    {
        if ( newMenu == _current )
            return;

        StartCoroutine( FadeMenu( _current, newMenu ) );
        _current = newMenu;
    }

    private IEnumerator FadeMenu( CanvasGroup from, CanvasGroup to )
    {
        float a = 1.0f;

        if ( from != null )
        {
            from.interactable = false;
            
            while ( a > 0.0f )
            {
                from.alpha = a;
                a -= Time.unscaledDeltaTime / _fadeTime;
                yield return null;
            }

            from.gameObject.SetActive(false);
            from.interactable = true;
            from.alpha = 1.0f;
        }
        
        to.gameObject.SetActive(true);
        to.alpha = 0.0f;
        to.interactable = false;
        
        a = 0;
        while ( a < 1.0f )
        {
            to.alpha = a;
            a += Time.unscaledDeltaTime / _fadeTime;
            yield return null;
        }

        to.alpha = 1.0f;
        to.interactable = true;
    }
}
