using UnityEngine;
using UnityEngine.UI;

namespace Utility.UIAdapter
{
    public class UIAdapterForScroll : MonoBehaviour
    {
        // public bool isUseSafeArea = true;
        public bool isUpdate;
        private CanvasScaler _canvasScaler;
        private RectTransform myRectTransform;
        private Vector2 offsetMin;
        private Vector2 offsetMax;
        public bool leftUseSafeArea;
        public bool rightUseSafeArea;
        public float magnification = 1;
        private void Awake()
        {
            _canvasScaler = GameObject.FindObjectOfType<CanvasScaler>();
            myRectTransform = GetComponent<RectTransform>();
          
        }

        void Start()
        {
            offsetMin = myRectTransform.offsetMin;
            offsetMax = myRectTransform.offsetMax;
            Execution();
        }


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

            Execution();
        }

        private void Execution()
        {
            RectTransform rectTransform = _canvasScaler.GetComponent<RectTransform>();
            float bl = rectTransform.sizeDelta.x / rectTransform.sizeDelta.y;
            float bl2 = _canvasScaler.referenceResolution.x / _canvasScaler.referenceResolution.y;
            if (bl > bl2)
            {
               
             
                if (leftUseSafeArea)
                {
                    var safeArea = Screen.safeArea;
                    float ratio =
                        _canvasScaler.referenceResolution.y * _canvasScaler.matchWidthOrHeight / Screen.height -
                        _canvasScaler.referenceResolution.x * (_canvasScaler.matchWidthOrHeight - 1) / Screen.width;
                    myRectTransform.offsetMin = new Vector2(offsetMin.x + safeArea.xMin * ratio/magnification, offsetMin.y);
                }
                if (rightUseSafeArea)
                {
                    var safeArea = Screen.safeArea;
                    float ratio =
                        _canvasScaler.referenceResolution.y * _canvasScaler.matchWidthOrHeight / Screen.height -
                        _canvasScaler.referenceResolution.x * (_canvasScaler.matchWidthOrHeight - 1) / Screen.width;
                    myRectTransform.offsetMax = new Vector2(offsetMax.x - safeArea.xMin * ratio/magnification, offsetMax.y);
                   
                }
              
            }
        }
    }
}