using Cryville.Common.Unity.UI;
using Cryville.Crtr.Browsing;
using UnityEngine;

namespace Cryville.Crtr {
	public class Menu : MonoBehaviour {
#pragma warning disable IDE0044
		[SerializeField]
		ResourceBrowserMaster m_browserMaster;
		[SerializeField]
		Animator m_targetAnimator;
		[SerializeField]
		ProgressBar m_progressBar;
		[SerializeField]
		SettingsPanel m_settingsPanel;
#pragma warning restore IDE0044

		bool initialized = false;
		int totalTasks = 0;
#pragma warning disable IDE0051
		void Awake() {
			Game.Init();
			transform.parent.Find("Canvas/Contents").gameObject.SetActive(true);
			m_settingsPanel.Target = Settings.Default;
		}
		void Update() {
			if (!initialized) {
				int taskCount = Game.NetworkTaskWorker.TaskCount;
				if (totalTasks < taskCount) totalTasks = taskCount;
				m_progressBar.value = 1 - (float)taskCount / totalTasks;
				if (taskCount == 0) {
					initialized = true;
					m_targetAnimator.SetTrigger("T_Main");
				}
			}
			if (Input.GetKeyDown(KeyCode.Escape)) {
				if (m_targetAnimator != null) Back();
			}
		}

		private static string animatorState = null;
		void OnDisable() {
			animatorState = m_targetAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.name;
		}
		void OnEnable() {
			Application.targetFrameRate = 60;
			if (animatorState != null) m_targetAnimator.PlayInFixedTime(animatorState, 0, 0);
			Game.NetworkTaskWorker.ResumeBackgroundTasks();
		}
#pragma warning restore IDE0051

		public void Back() {
			if (m_browserMaster.Back()) return;
			m_targetAnimator.SetTrigger("G_Back");
		}
		public void Quit() {
			Application.Quit();
		}
	}
}
