using Cryville.Common.Unity.UI;
using Cryville.Crtr.Config.UI;
using Cryville.Crtr.UI;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Cryville.Crtr.Browsing.UI {
	public class ResourceBrowserMaster : MonoBehaviour {
		[SerializeField]
		private Button m_playButton;
		[SerializeField]
		private Button m_configButton;
		[SerializeField]
		private ConfigPanelMaster m_configPanel;

		private DockLayoutGroup _group;
		public ResourceBrowser MainBrowser { get; private set; }
		private DetailPanel _detailPanel;
		readonly List<ResourceBrowserUnit> _units = new List<ResourceBrowserUnit>();

#pragma warning disable IDE0051
		void Awake() {
			_group = GetComponent<DockLayoutGroup>();
			MainBrowser = transform.GetChild(0).GetComponent<ResourceBrowser>();
			MainBrowser.ResourceManager = new LegacyResourceManager(Settings.Default.GameDataPath);
			_detailPanel = transform.GetChild(1).GetComponent<DetailPanel>();
			_units.Add(MainBrowser);
			_units.Add(_detailPanel);
		}

		int _slideDest = 0;
		void Update() {
			var cv = _group.SlideIndex;
			_group.SlideIndex = (cv - _slideDest) * 0.86f + _slideDest;
		}
#pragma warning restore IDE0051

		public void ShowDetail(int id, ChartDetail detail) {
			SlideIntoView(1);
			_detailPanel.Load(id, detail);
			m_playButton.gameObject.SetActive(true);
			m_configButton.gameObject.SetActive(true);
		}

		/*[Obsolete]
		public void ShowSettings(int id, ChartDetail detail) {
			SlideIntoView(2);
			_settingsPanel.Load(id, detail);
		}*/

		public bool Back() {
			if (_slideDest == 0) return false;
			SlideIntoView(_slideDest - 1);
			return true;
		}

		private void SlideIntoView(int v) {
			v = Mathf.Clamp(v, 0, _units.Count - 1);
			var cv = _group.SlideIndex;
			if (cv < v) _slideDest = v - 1;
			else _slideDest = v;
			_units[_slideDest].SlideToLeft();
			_units[_slideDest + 1].SlideToRight();
		}

		public void Open(int id, ChartDetail detail) {
			SetDataSettings(id, detail);
#if UNITY_5_3_OR_NEWER
			SceneManager.LoadScene("Play", LoadSceneMode.Additive);
#else
			Application.LoadLevelAdditive("Play");
#endif
			GameObject.Find("/Master").GetComponent<Master>().HideMenu();
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
			DiscordController.Instance.SetPlaying(string.Format("{0} - {1}", detail.Meta.song.name, detail.Meta.name), detail.Meta.length);
#endif
		}

		public void OpenConfig(int id, ChartDetail detail) {
			SetDataSettings(id, detail);
		}

		void SetDataSettings(int id, ChartDetail detail) {
			Settings.Default.LoadRuleset = detail.Meta.ruleset + "/.umgr";
			Settings.Default.LoadRulesetConfig = detail.Meta.ruleset + ".json";
			Settings.Default.LoadChart = MainBrowser.ResourceManager.GetItemPath(id);
		}
	}
}
