using UnityEngine;
using UnityEngine.EventSystems;

namespace Camera
{
	public class SafeAreaCanvas : UIBehaviour {
    
		public bool useSafeAreaOverride;
		public Rect safeAreaOverride;
	
		public bool useResolutionOverride;
		public Vector2 resolutionOverride;
	
		private RectTransform rectTransform;
		public RectTransform RectTransform
		{
			get
			{
				if (rectTransform == null)
					rectTransform = GetComponent<RectTransform>();
				return rectTransform;
			}
		}

		public Rect SafeArea
		{
			get
			{
#if UNITY_EDITOR
				return useSafeAreaOverride ? safeAreaOverride : Screen.safeArea;
#else
		return Screen.safeArea;
#endif
			}
		}
	
		public Vector2 ScreenResolution
		{
			get
			{
#if UNITY_EDITOR
				return useResolutionOverride ? resolutionOverride : new Vector2(Screen.width, Screen.height);
#else
		return new Vector2(Screen.width, Screen.height);
#endif
			}
		}

		protected override void Start()
		{
			base.Start();
			UpdateSafeArea();
		}

		protected override void OnCanvasHierarchyChanged()
		{
			UpdateSafeArea();
		}

		void UpdateSafeArea()
		{
			RectTransform.anchorMin = Vector2.zero;
			RectTransform.anchorMax = Vector2.one;
		
			RectTransform.offsetMin = new Vector2((SafeArea.xMin / ScreenResolution.x) * RectTransform.rect.width, (SafeArea.yMin / ScreenResolution.y) * RectTransform.rect.height);
			RectTransform.offsetMax = new Vector2((SafeArea.xMax / ScreenResolution.x) * RectTransform.rect.width - RectTransform.rect.width, (SafeArea.yMax / ScreenResolution.y) * RectTransform.rect.height - RectTransform.rect.height);
		}
	}
}