using Cryville.Common;
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Cryville.Crtr.Browsing.UI {
	public class DetailPanel : ResourceBrowserUnit {
#pragma warning disable IDE0044
		[SerializeField]
		private Sprite m_coverPlaceholder;
#pragma warning restore IDE0044

		int _id;
		ChartDetail _data;
		GameObject _placeholder;
		GameObject _outerContent;
		Transform _content;
		Image _cover;
		TMP_Text _title;
		TMP_Text _desc;

		protected override void Awake() {
			base.Awake();
			_placeholder = transform.Find("__placeholder__").gameObject;
			_outerContent = transform.Find("__content__").gameObject;
			_content = _outerContent.transform.Find("__content__");
			_cover = _content.Find("Cover").GetComponent<Image>();
			_title = _content.Find("Texts/Title").GetComponent<TMP_Text>();
			_desc = _content.Find("Texts/Description").GetComponent<TMP_Text>();
		}
		void OnDestroy() {
			if (_data.Cover != null) _data.Cover.Cancel();
			if (_cover.sprite != null && _cover.sprite != m_coverPlaceholder) {
				Texture2D.Destroy(_cover.sprite.texture);
				Sprite.Destroy(_cover.sprite);
			}
		}
		public void Load(int id, ChartDetail data) {
			_id = id;
			_placeholder.SetActive(false);
			_outerContent.SetActive(true);
			OnDestroy();
			_data = data;
			_cover.sprite = m_coverPlaceholder;
			if (data.Cover != null) data.Cover.Destination = DisplayCover;
			var meta = data.Meta;
			_title.text = string.Format("{0}\n{1}", meta.song.name, meta.name);
			_desc.text = string.Format(
				"Music artist: {0}\nCharter: {1}\nLength: {2}\nNote Count: {3}",
				meta.song.author, meta.author,
				TimeSpan.FromSeconds(meta.length).ToString(3), meta.note_count
			);
		}
		private void DisplayCover(bool succeeded, Texture2D tex) {
			if (succeeded) {
				_cover.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero, 160, 0, SpriteMeshType.FullRect);
			}
		}
		public void OnPlay() {
			Master.Open(_id, _data);
		}
		public void OnConfig() {
			Master.OpenConfig(_id, _data);
		}
	}
}
