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

public class UIAdapterForScale : MonoBehaviour
{
    public bool isUseSafeArea = true;
    public bool isUpdate;

    private CanvasScaler _canvasScaler;

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

    void Start()
    {
        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)
        {
            float v = bl - bl2;
            float addX = (v * rectTransform.sizeDelta.x) / 2;
            if (isUseSafeArea)
            {
                var safeArea = Screen.safeArea;
                float ratio = _canvasScaler.referenceResolution.y * _canvasScaler.matchWidthOrHeight / Screen.height -
                              _canvasScaler.referenceResolution.x * (_canvasScaler.matchWidthOrHeight - 1) / Screen.width;
                addX -= safeArea.xMin * ratio;
            }

            myRectTransform.sizeDelta = new Vector2(sizeData.x + addX, sizeData.y);
        }
    }
}