using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneController : MonoBehaviour
{
    public CanvasGroup faderCanvasGroup;
    public float fadeDuration = 1f;
    public string startingSceneName = "Cyber";
    private bool isFading;
    private string currentScene = string.Empty;

    private IEnumerator Start()
    {
        faderCanvasGroup.alpha = 0f;
        yield return FadeAndSwitchScenes(startingSceneName);
    }

    public void FadeAndLoadScene(string sceneName)
    {
        if (!isFading)
        {
            StartCoroutine(FadeAndSwitchScenes(sceneName));
        }
    }

    private IEnumerator FadeAndSwitchScenes(string sceneName)
    {
        Scene newScene = SceneManager.GetSceneByName(sceneName);
        if (newScene.isLoaded == false)
        {
            yield return StartCoroutine(Fade(1f));
            if (currentScene != string.Empty)
                yield return SceneManager.UnloadSceneAsync(currentScene);
            yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
            newScene = SceneManager.GetSceneByName(sceneName);
            SceneManager.SetActiveScene(newScene);
            yield return StartCoroutine(Fade(0f));
        }
        else
        {
            newScene = SceneManager.GetSceneByName(sceneName);
            SceneManager.SetActiveScene(newScene);
        }
        currentScene = newScene.name;
    }

    private IEnumerator Fade(float finalAlpha)
    {
        isFading = true;

        // Make sure the CanvasGroup blocks raycasts into the scene so no more input can be accepted.
        faderCanvasGroup.blocksRaycasts = true;

        float fadeSpeed = Mathf.Abs(faderCanvasGroup.alpha - finalAlpha) / fadeDuration;

        while (!Mathf.Approximately(faderCanvasGroup.alpha, finalAlpha))
        {
            faderCanvasGroup.alpha = Mathf.MoveTowards(faderCanvasGroup.alpha, finalAlpha,
                fadeSpeed * Time.deltaTime);

            // Wait for a frame then continue.
            yield return null;
        }

        isFading = false;

        // Stop the CanvasGroup from blocking raycasts so input is no longer ignored.
        faderCanvasGroup.blocksRaycasts = false;
    }
}
