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

namespace Cryville.Crtr.Browsing {
	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;
		DockOccupiedRatioLayoutGroup _outerContentGroup;
		Transform _content;
		Image _cover;
		Text _title;
		Text _desc;

		protected override void Awake() {
			base.Awake();
			_placeholder = transform.Find("__placeholder__").gameObject;
			_outerContent = transform.Find("__content__").gameObject;
			_outerContentGroup = _outerContent.GetComponent<DockOccupiedRatioLayoutGroup>();
			_content = _outerContent.transform.Find("__content__");
			_cover = _content.Find("Cover").GetComponent<Image>();
			_title = _content.Find("Texts/Title").GetComponent<Text>();
			_desc = _content.Find("Texts/Description").GetComponent<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.chart.name);
			_desc.text = string.Format(
				"Music artist: {0}\nCharter: {1}\nLength: {2}\nNote Count: {3}",
				meta.song.author, meta.chart.author,
				TimeSpan.FromSeconds(meta.chart.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);
			}
		}
		public void OnPlay() {
			Master.Open(_id, _data);
		}
		public void OnConfig() {
			Master.OpenConfig(_id, _data);
		}
	}
}