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

namespace Cryville.EEW.Unity.Map.Element {
	class MultiLineElement : MapElement {
		[SerializeField] LineRenderer m_lineRendererPrefab;
		readonly List<LineRenderer> _lineRenderers = new();

		RectangleF? m_AABB;
		public override RectangleF? AABB => m_AABB;

		[SerializeField]
		Color m_color = Color.white;
		public Color Color {
			get => m_color;
			set {
				if (m_color == value) return;
				m_color = value;
				foreach (var r in _lineRenderers) {
					r.Color = value;
				}
			}
		}
		[SerializeField]
		float m_width = 1;
		public float Width {
			get => m_width;
			set {
				if (m_width == value) return;
				m_width = value;
				foreach (var r in _lineRenderers) {
					r.Width = value * ComputedScale / 512;
				}
			}
		}

		protected override void OnSetScale() {
			foreach (var r in _lineRenderers) {
				r.Width = m_width * ComputedScale / 512;
			}
		}
		protected override void OnSetMaterial(Material material) {
			foreach (var r in _lineRenderers) {
				r.Material = Material;
				r.Color = m_color;
			}
		}

		public void SetLines(IEnumerable<IEnumerable<PointF>> lines, ref int order) {
			foreach (var r in _lineRenderers) {
				Destroy(r.gameObject);
			}
			_lineRenderers.Clear();
			m_AABB = null;
			foreach (var line in lines) {
				CreateLine(line, ref order);
			}
		}

		void CreateLine(IEnumerable<PointF> line, ref int order) {
			_lineRenderers.Add(LineRenderer.Create(line, OrderToZ(ref order), m_lineRendererPrefab, Material, m_color, m_width, this, out var aabb));
			if (aabb is RectangleF b) {
				m_AABB = m_AABB is RectangleF a ? MapTileUtils.UnionTileAABBs(a, b) : b;
			}
		}
	}
}
