using Mox.Shared.Math;
using Mox.Shared.Renderer;

namespace Mox.Shared.UI
{
	public class Label : Control
	{
		public Label()
		{
			IsHitTestVisible = false;
		}

		public override void Render()
		{
			RendererBase.Instance.SetTextStyle(Font, FontSize);
			RendererBase.Instance.SetTextColor(FontColor);
			RendererBase.Instance.DrawText(Text, LayoutedRect.Left + LayoutedRect.Width / 2, LayoutedRect.Top + LayoutedRect.Height / 2);
		}

		public override void Serialize(Serializer.Serializer _serializer)
		{
			_serializer.Serialize(ref m_sText, nameof(Text), null);
			_serializer.Serialize(ref m_sFont, nameof(Font), null);
			_serializer.Serialize(ref m_iFontSize, nameof(FontSize), 0);
			_serializer.Serialize(ref m_FontColor, nameof(FontColor), null);

			base.Serialize(_serializer);
		}

		private void UpdateTextMeasure()
		{
			if (!m_bMeasureDirty)
			{
				return;
			}

			m_bMeasureDirty = false;
			RendererBase.Instance.SetTextStyle(Font, FontSize);
			m_Measure = RendererBase.Instance.MeasureText(Text);
		}
		
		public string Text
		{
			get => m_sText;
			set
			{
				m_sText = value;
				m_bMeasureDirty = true;
				Root.Instance.InvalidateLayout();
			}
		}

		public string Font
		{
			get => m_sFont;
			set
			{
				m_sFont = value;
				m_bMeasureDirty = true;
				Root.Instance.InvalidateLayout();
			}
		}

		public int FontSize
		{
			get => m_iFontSize;
			set
			{
				m_iFontSize = value;
				m_bMeasureDirty = true;
				Root.Instance.InvalidateLayout();
			}
		}

		public override Measure MinWidth
		{
			get
			{
				UpdateTextMeasure();
				return new Measure(m_Measure.Width, EUnit.Pixel);
			}
		}

		public override Measure MinHeight
		{
			get
			{
				UpdateTextMeasure();
				return new Measure(m_Measure.Height, EUnit.Pixel);
			}
		}

		public Color FontColor { get => m_FontColor; set => m_FontColor = value; }

		private string m_sText;
		private string m_sFont = "System";
		private int m_iFontSize = 8;
		private Color m_FontColor = new Color(1, 0, 0, 1);
		private Rect m_Measure;
		private bool m_bMeasureDirty = true;
	}
}
