using Cryville.Common.Unity.UI;
using Cryville.Crtr.Browsing.UI;
using Cryville.Crtr.Config;
using Cryville.Crtr.Config.UI;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using unity = UnityEngine;

namespace Cryville.Crtr.UI {
	public class Menu : MonoBehaviour {
#pragma warning disable IDE0044
		[SerializeField]
		ResourceBrowserMaster m_browserMaster;
		[SerializeField]
		Animator m_targetAnimator;
		[SerializeField]
		ProgressBar m_progressBar;
		[SerializeField]
		PropertyMasterPanel m_settingsPanel;
		[SerializeField]
		TMP_Text m_title;
		[SerializeField]
		GameObject[] m_backBlockingObjects;
#pragma warning restore IDE0044

		int frameIndex = 2;
		bool initialized = false;
		int totalTasks = 0;
#pragma warning disable IDE0051
		void Awake() {
			Game.Init();
			transform.parent.Find("Canvas/Contents").gameObject.SetActive(true);
			m_settingsPanel.Adapter = new DefaultPropertyMasterAdapter(Settings.Default);
			PushTitle("Chart Browser");
		}
		void Update() {
			if (!initialized) {
				int taskCount = Game.NetworkTaskWorker.TaskCount;
				if (totalTasks < taskCount) totalTasks = taskCount;
				if (frameIndex > 0) {
					frameIndex--;
					return;
				}
				m_progressBar.value = totalTasks == 0 ? 1 : (1 - (float)taskCount / totalTasks);
				if (taskCount == 0) {
					initialized = true;
					m_targetAnimator.SetTrigger("T_Main");
				}
			}
			if (unity::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.ResumeBackgroundTasks();
		}
#pragma warning restore IDE0051

		readonly Stack<string> _uiStack = new Stack<string>();
		public void PushTitle(string title) {
			_uiStack.Push(title);
			m_title.SetText(title);
		}
		public void Back() {
			foreach (var obj in m_backBlockingObjects) {
				if (obj.activeInHierarchy) return;
			}
			if (m_browserMaster.Back()) return;
			m_targetAnimator.SetTrigger("G_Back");
			if (_uiStack.Count <= 1) return;
			_uiStack.Pop();
			m_title.SetText(_uiStack.Peek());
		}
		public void Quit() {
			Application.Quit();
		}
	}
}
