using UnityEngine;
using UnityEngine.EventSystems;

namespace Cryville.Common.Unity.UI {
	[ExecuteAlways]
	[RequireComponent(typeof(RectTransform))]
	public class SafeArea : UIBehaviour {
		bool _delayedUpdate;
		protected override void OnValidate() {
			_delayedUpdate = true;
		}
		void Update() {
			if (_delayedUpdate) {
				_delayedUpdate = false;
				UpdateRect();
			}
		}
		protected override void OnRectTransformDimensionsChange() {
			base.OnRectTransformDimensionsChange();
			UpdateRect();
		}
		protected override void OnTransformParentChanged() {
			base.OnTransformParentChanged();
			UpdateRect();
		}
		void UpdateRect() {
			var safeArea = Screen.safeArea;
			var rectTransform = transform as RectTransform;
			var canvas = GetComponentInParent<Canvas>(true).transform as RectTransform;
			RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, new Vector2(safeArea.xMin, safeArea.yMin), Camera.main, out var pt1);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, new Vector2(safeArea.xMax, safeArea.yMax), Camera.main, out var pt2);
			var result = Rect.MinMaxRect(pt1.x, pt1.y, pt2.x, pt2.y);
			rectTransform.anchoredPosition = result.center;
			rectTransform.sizeDelta = result.size;
			rectTransform.anchorMin = rectTransform.anchorMax = rectTransform.pivot = new Vector2(0.5f, 0.5f);
		}
	}
}
