using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace RothenburgAR.UI
{
    /// <summary>
    /// Assuming that all children of this object are anchored to the center, this behaviour will move the object away from any border to have the specified padding
    /// </summary>
    public class PercentualPaddingBehaviour : MonoBehaviour
    {
        public float Padding = 0.01f;

        void Start()
        {
            DisplayManager.Instance.OnOrientationChange.AddListener(RecalculateTransform);
            DisplayManager.Instance.OnResolutionChange.AddListener(RecalculateTransform);
            RecalculateTransform();
        }

        void OnDestroy()
        {
            DisplayManager.Instance.OnOrientationChange.RemoveListener(RecalculateTransform);
            DisplayManager.Instance.OnResolutionChange.RemoveListener(RecalculateTransform);
        }
            
        public void RecalculateTransform()
        {
            var transform = this.GetComponent<RectTransform>();
            float desiredPadding = Mathf.Max(Screen.height, Screen.width) * Padding;

            // make object square
            var size = Mathf.Min(transform.rect.width, transform.rect.height);
            transform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size);
            transform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, size);

            // set padding when applicable
            if (transform.anchorMax.y >= 0.99f) transform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, desiredPadding, size);
            if (transform.anchorMax.x >= 0.99f) transform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, desiredPadding, size);
            if (transform.anchorMin.y <= 0.01f) transform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, desiredPadding, size);
            if (transform.anchorMin.x <= 0.01f) transform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, desiredPadding, size);
        }
    }
}