using Cryville.EEW.Core.Map;
using System.Drawing;
using TMPro;
using UnityEngine;
using Color = UnityEngine.Color;

namespace Cryville.EEW.Unity.Map.Element {
	[RequireComponent(typeof(SpriteRenderer))]
	class LabeledPointElement : MapElement {
		[SerializeField] Sprite m_sprite;
		[SerializeField] Sprite m_spriteArea;
		[SerializeField] TextMeshPro m_textMesh;

		PointF _tilePos;
		public override RectangleF? AABB => new(_tilePos, SizeF.Empty);

		public void SetLocation(PointF location, ref int order) {
			_tilePos = MapTileUtils.WorldToTilePos(location);
			Vector3 pos = _tilePos.ToVector2();
			pos.z = OrderToZ(ref order);
			transform.localPosition = pos;
		}

		[SerializeField]
		string m_text = "";
		public string Text {
			get => m_text;
			set {
				if (m_text == value) return;
				m_text = value;
				m_textMesh.text = value;
			}
		}

		[SerializeField]
		Color m_color = Color.white;
		public Color Color {
			get => m_color;
			set {
				if (m_color == value) return;
				m_color = value;
				_spriteRenderer.color = value;
			}
		}

		[SerializeField]
		Color m_textColor = Color.black;
		public Color TextColor {
			get => m_textColor;
			set {
				if (m_textColor == value) return;
				m_textColor = value;
				m_textMesh.color = value;
			}
		}

		bool m_isArea;
		public bool IsArea {
			get => m_isArea;
			set {
				if (m_isArea == value) return;
				m_isArea = value;
				_spriteRenderer.sprite = value ? m_spriteArea : m_sprite;
			}
		}

		float m_size;
		public float Size {
			get => m_size;
			set {
				if (m_size == value) return;
				m_size = value;
				OnSetScale();
			}
		}

		SpriteRenderer _spriteRenderer;
		void Awake() {
			_spriteRenderer = GetComponent<SpriteRenderer>();
			m_textMesh.text = m_text;
			_spriteRenderer.color = m_color;
			m_textMesh.color = m_textColor;
			_spriteRenderer.sprite = m_isArea ? m_spriteArea : m_sprite;
		}

		protected override void OnSetScale() {
			transform.localScale = ComputedScale * m_size / 256 * Vector3.one;
		}
	}
}
