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

namespace Cryville.EEW.Unity.Map.Element {
	class GroupElement : MapElement {
		protected virtual Transform Container => transform;

		readonly List<MapElement> _elements = new();

		public override RectangleF? AABB {
			get {
				RectangleF? ret = null;
				foreach (var element in _elements) {
					if (element == null) continue;
					if (element.AABB is not RectangleF aabb) continue;
					if (ret == null) ret = aabb;
					else ret = MapTileUtils.UnionTileAABBs(ret.Value, aabb);
				}
				return ret;
			}
		}

		public virtual void AddElement(MapElement element) {
			if (element == null) return;
			element.Scale = Scale;
			if (element.InheritMaterial) element.Material = Material;
			element.transform.SetParent(Container, false);
			_elements.Add(element);
		}

		protected override void OnSetScale() {
			foreach (Transform element in Container) {
				element.GetComponent<MapElement>().Scale = Scale;
			}
		}
		protected override void OnSetMaterial(Material material) {
			foreach (Transform child in Container) {
				var element = child.GetComponent<MapElement>();
				if (element.InheritMaterial) element.Material = Material;
			}
		}
	}
}
