using Cryville.Common.Unity;
using Cryville.Common.Unity.UI;
using Cryville.EEW.Report;
using System.Globalization;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

namespace Cryville.EEW.Unity.UI {
	class EventOngoingView : MonoBehaviour {
		[SerializeField] Image[] m_reportView;

		[SerializeField] Button m_button;
		[SerializeField] TMPLocalizedText m_textView;

		[SerializeField] DockOccupiedRatioLayoutGroup m_dockLayoutGroup;

		ReportViewModel _viewModel;

		void SetSeverity(float severity) {
			var color = SharedSettings.Instance.SeverityColorMapping.From(severity);
			SetMainColor(color.ToSrgb().ToUnityColor());
		}
		protected virtual void SetMainColor(Color color) {
			foreach (var view in m_reportView)
				view.color = color;
		}
		void SetView(float mainSeverity, string title, string location, CultureInfo culture) {
			SetSeverity(mainSeverity);
			SetText(m_textView, string.Format("{0}  {1}", title, location), culture);
		}
		static void SetText(TMPLocalizedText view, string text, CultureInfo culture) {
			if (string.IsNullOrWhiteSpace(text)) {
				view.gameObject.SetActive(false);
				return;
			}
			view.gameObject.SetActive(true);
			view.SetText(text, culture);
		}

		public void SetViewModel(ReportViewModel e) {
			_viewModel = e;
			SetView(e.Properties.FirstOrDefault()?.Severity ?? -1, e.Title, e.Location, e.Culture);
		}

		PropertyTweener<float> _dockRatioTweener;
		void Awake() {
			_dockRatioTweener = new(() => m_dockLayoutGroup.DockOccupiedRatio, v => m_dockLayoutGroup.DockOccupiedRatio = v, Tweeners.Single);
		}
		void Start() {
			m_button.onClick.AddListener(OnViewClicked);
		}
		void OnViewClicked() {
			EventOngoingListView.Instance.OnItemClicked(_viewModel);
		}
		void Update() {
			_dockRatioTweener.Advance(Time.deltaTime);
		}
		public void SetCurrent(bool v) {
			_dockRatioTweener.Start(v ? 1 : 0.75f, 0.1f);
		}
	}
}
