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

namespace Cryville.EEW.Unity.UI {
	class EventReportView : EventBaseView {
		[SerializeField] Button m_reportViewButton;
		[SerializeField] TMPLocalizedText m_titleView;
		[SerializeField] GameObject m_revisionViewContainer;
		[SerializeField] TMPLocalizedText m_revisionView;
		ReportViewModel _viewModel;

		protected virtual void Start() {
			if (m_reportViewButton != null) m_reportViewButton.onClick.AddListener(OnViewClicked);
		}
		void OnViewClicked() {
			Worker.Instance.SetSelected(_viewModel);
		}
		public virtual void SetViewModel(ReportViewModel viewModel, bool hideRevisionByDefault = false) {
			_viewModel = viewModel;
			bool hideRevision = hideRevisionByDefault && ShouldHideRevision(viewModel.RevisionKey);

			if (m_titleView != null) {
				var title = viewModel.Title ?? "";
				if (!string.IsNullOrWhiteSpace(viewModel.Source))
					title += " | " + viewModel.Source;
				SetText(m_titleView, title, viewModel.Culture);
			}

			if (!hideRevision && viewModel.RevisionKey is IReportRevisionKey rev) {
				using var lres = CoreMessages.Generic(viewModel.Culture);
				var res = lres.RootMessageStringSet;
				m_revisionViewContainer.SetActive(true);
				if (rev.IsCancellation)
					SetText(m_revisionView, res.GetString("SerialCancel") ?? "-", viewModel.Culture);
				else
					SetText(m_revisionView, string.Format(viewModel.Culture, res.GetString(rev.IsFinalRevision ? "SerialFinal" : "Serial") ?? "#{0}", rev.Serial), viewModel.Culture);
			}
			else {
				m_revisionViewContainer.SetActive(false);
				SetText(m_revisionView, null, viewModel.Culture);
			}

			var keyProp = viewModel.Properties.FirstOrDefault();
			var props = viewModel.Properties.Skip(1);
			SetView(
				keyProp?.Severity ?? -1,
				new Localized<string>(viewModel.Location, viewModel.Culture),
				new Localized<string>(viewModel.Predicate, viewModel.Culture),
				new Localized<DateTime?>(viewModel.Time, viewModel.Culture), viewModel.TimeZone,
				new Localized<ReportViewModelProperty>(keyProp, viewModel.Culture),
				props.Select(i => new Localized<ReportViewModelProperty>(i, viewModel.Culture))
			);
		}

		static bool ShouldHideRevision(IReportRevisionKey key) {
			return key == null || (key.Serial == null && !key.IsCancellation && !key.IsFinalRevision);
		}
	}
}
