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

namespace Cryville.Crtr.Browsing {
	public class ResourceBrowser : ResourceBrowserUnit {
		public IResourceManager<ChartDetail> ResourceManager;
		public ScrollableItemGrid PathContainer;
		public ScrollableItemGrid ItemContainer;

		FileDialog _dialog;

		protected void Start() {
			PathContainer.LoadItem = LoadPathPart;
			ItemContainer.LoadItem = LoadItem;
			ItemContainer.ItemCount = ResourceManager.ChangeDirectory(new string[] { "" });
			PathContainer.ItemCount = ResourceManager.CurrentDirectory.Length;

			_dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
			_dialog.gameObject.SetActive(false);
		}

		private bool LoadPathPart(int id, GameObject obj) {
			var item = ResourceManager.CurrentDirectory[id];
			obj.GetComponent<PathPart>().Load(id, item);
			return true;
		}

		private bool LoadItem(int id, GameObject obj) {
			var bi = obj.GetComponent<BrowserItem>();
			var item = ResourceManager.GetItemMeta(id);
			bi.Load(id, item);
			return true;
		}

		public void OnDirectoryItemClicked(int id) {
			ItemContainer.ItemCount = ResourceManager.OpenDirectory(id);
			PathContainer.ItemCount = ResourceManager.CurrentDirectory.Length;
			if (PathContainer.ItemCount >= PathContainer.VisibleLines - 1)
				PathContainer.GetComponentInParent<ScrollRect>().velocity = new Vector2(-Screen.width, 0);
		}

		public void OnObjectItemClicked(int id) {
			Master.ShowDetail(id, ResourceManager.GetItemDetail(id));
		}

		public void OnPathClicked(int id) {
			ItemContainer.ItemCount = ResourceManager.ReturnToDirectory(id);
			PathContainer.ItemCount = ResourceManager.CurrentDirectory.Length;
		}

		public void OnAddButtonClicked() {
			_dialog.Callback = OnAddDialogClosed;
			_dialog.Filter = ResourceManager.GetSupportedFormats();
			_dialog.Show();
		}

		private void OnAddDialogClosed() {
			if (_dialog.FileName == null) return;
			if (ResourceManager.ImportItemFrom(_dialog.FileName)) {
				Popup.Create("Import succeeded");
				OnPathClicked(ResourceManager.CurrentDirectory.Length - 1);
			}
			else {
				Popup.Create("Import failed");
			}
		}
	}
}
