using UnityEngine;
using UnityEngine.UI;

namespace Cryville.Crtr.Browsing {
	internal class BrowserItemTile : BrowserItem {
#pragma warning disable IDE0044
		[SerializeField]
		private Sprite m_iconPlaceholder;
#pragma warning restore IDE0044

		private bool _dir;
		private Image _icon;
		private Text _title;
		private Text _desc;

#pragma warning disable IDE0051
		void Awake() {
			_icon = transform.Find("__content__/Icon").GetComponent<Image>();
			_title = transform.Find("__content__/Texts/Title/__text__").GetComponent<Text>();
			_desc = transform.Find("__content__/Texts/Description/__text__").GetComponent<Text>();
		}
		void OnDestroy() {
			if (meta.Icon != null) meta.Icon.Cancel();
			if (_icon.sprite != null && _icon.sprite != m_iconPlaceholder) {
				Texture2D.Destroy(_icon.sprite.texture);
				Sprite.Destroy(_icon.sprite);
			}
		}
#pragma warning restore IDE0051

		internal override void Load(int id, ResourceItemMeta item) {
			OnDestroy();
			base.Load(id, item);
			_dir = meta.IsDirectory;
			_icon.sprite = m_iconPlaceholder;
			if (meta.Icon != null) meta.Icon.Destination = DisplayCover;
			_title.text = meta.Name;
			_desc.text = string.Format("{0}\n{1}", meta.DescriptionMain, meta.DescriptionSub);
		}
		private void DisplayCover(bool succeeded, Texture2D tex) {
			if (succeeded) {
				_icon.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
			}
		}
		public void OnClick() {
			if (Id == null) return;
			ResourceBrowser resourceBrowser = GetComponentInParent<ResourceBrowser>();
			if (_dir) resourceBrowser.OnDirectoryItemClicked(Id.Value);
			else resourceBrowser.OnObjectItemClicked(Id.Value);
		}
	}
}