using UnityEngine;
using UnityEngine.UI;

namespace Utility.UIAdapter
{
    public class UIAdapterForSafeArea : MonoBehaviour
    {
        public enum AnchorPointType
        {
            Left,
            Right,
        }

        [Header("固定偏移")] public float offsetX;

        // public int minAdapter=100;
        public AnchorPointType anchorPointType;

        // public bool isUseSafeArea = true;
        public bool isUpdate;

        private CanvasScaler _canvasScaler;

        private RectTransform myRectTransform;
        private Vector2 anchoredPosition;

        private void Awake()
        {
            _canvasScaler = GameObject.FindObjectOfType<CanvasScaler>();
            myRectTransform = GetComponent<RectTransform>();
            anchoredPosition = myRectTransform.anchoredPosition;
        }

        void Start()
        {
            Execution();
        }


        void Update()
        {
            if (!isUpdate)
            {
                return;
            }

            Execution();
        }

        private void Execution()
        {
            var safeArea = Screen.safeArea;
            float ratio = _canvasScaler.referenceResolution.y * _canvasScaler.matchWidthOrHeight / Screen.height -
                          _canvasScaler.referenceResolution.x * (_canvasScaler.matchWidthOrHeight - 1) / Screen.width;
            if (anchorPointType == AnchorPointType.Left)
            {
                if (safeArea.xMin > 0)
                {
                    if (offsetX > 0)
                    {
                        myRectTransform.anchoredPosition =
                            new Vector2(anchoredPosition.x + offsetX, anchoredPosition.y);
                    }
                    else
                    {
                        myRectTransform.anchoredPosition =
                            new Vector2(anchoredPosition.x + safeArea.xMin * ratio, anchoredPosition.y);
                    }
                }
            }
            else
            {
                if (safeArea.xMin > 0)
                {
                    if (offsetX > 0)
                    {
                        myRectTransform.anchoredPosition =
                            new Vector2(anchoredPosition.x - offsetX, anchoredPosition.y);
                    }
                    else
                    {
                        myRectTransform.anchoredPosition =
                            new Vector2(anchoredPosition.x - safeArea.xMin * ratio, anchoredPosition.y);
                    }
                }
            }
        }
    }
}