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

namespace Nostalgia.Example
{
	[AddComponentMenu("Nostalgia/Example/Title")]
	public sealed class Title : MonoBehaviour
	{
		public Player _Player;
		public GameObject _InGameUI;
		public Text _RecordText;
		public GameObject _PressStartButton;
		public GameObject _RecordResetButton;
		public UnityEvent beginGameEvent = new UnityEvent();

		private static readonly string _RecordTimePrefsKey = "RecordTime";

		void Start()
		{
			Time.timeScale = 0.0f;
			if (PlayerPrefs.HasKey(_RecordTimePrefsKey))
			{
				float recordTime = PlayerPrefs.GetFloat(_RecordTimePrefsKey);
				_RecordText.text = recordTime.ToString("F3");
				_RecordResetButton.SetActive(true);
			}
			else
			{
				_RecordText.text = "----";
			}

			_InGameUI.SetActive(false);

			StartCoroutine(WaitSubmit());
		}

		IEnumerator WaitSubmit()
		{
			_PressStartButton.SetActive(false);

			while ( !SplashScreen.isFinished )
			{
				yield return null;
			}

			yield return null;

			VirtualInput.ResetInputAxes();

			_PressStartButton.SetActive(true);
		}

		public void OnPressStart()
		{
			_Player.enabled = true;
			_InGameUI.SetActive(true);
			Time.timeScale = 1.0f;
			beginGameEvent.Invoke();
			Destroy(gameObject);
		}

		public void OnRecordReset()
		{
			PlayerPrefs.DeleteKey(_RecordTimePrefsKey);
			_RecordText.text = "----";
		}
	}
}
