using Assets.Scripts.Core;
using Assets.Scripts.Events;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TitleScreen : MonoBehaviour {
    [SerializeField] private Text _buttonText;
    private bool _leaving;
    private int _option;
    private bool _done;

    private delegate void RunAfter();

    protected void Start() {
        FadeController.Instance.FadeIn(2.0f);
        MusicController.Instance.PlayTitle();
    }

    public void OnButtonClicked() {
        if (_done) {
            return;
        }
        _done = true;

        switch (_option) {
            case 0:
                FadeThen(() => Application.LoadLevel(1));
                break;
            case 1:
                FadeThen(() => Application.LoadLevel(2));
                break;
            case 2:
                FadeThen(Application.Quit);
                break;
        }
    }

    public void OnLeftClicked () {
        _option = (_option + 4) % 3;
        UpdateButton();
    }

    public void OnRightClicked () {
        _option = (_option + 1) % 3;
        UpdateButton();
    }

    private void UpdateButton () {
        _buttonText.text = _option == 0 ? "PLAY" : (_option == 1 ? "CREDITS" : "EXIT");
    }

    private void FadeThen (RunAfter a) {
        if (!_leaving) {
            _leaving = true;
            StartCoroutine(DoFadeThen(a));
        }
    }

    private IEnumerator DoFadeThen(RunAfter runAfter) {
        FadeController.Instance.FadeOut(2.0f);
        yield return new WaitForSeconds(2.5f);
        runAfter();
    }
}
