using Coffee.UIExtensions;
using UnityEngine;
using UnityEngine.UI;

namespace MyGame.Scripts
{
    public class TutorialObjectMask : MonoBehaviour
    {
        [SerializeField] private Unmask unmask;
        [SerializeField] private Unmask unmaskArrow;
        [SerializeField] private Image unMaskImage;
        [SerializeField] private Image backgroundImage;
        [SerializeField] private Animator arrowAnimator;
        private static readonly int Under = Animator.StringToHash("Under");

        public void SetTarget(RectTransform rectTransform)
        {
            unmask.FitTo(rectTransform);
        }

        public void SetSprite(Sprite sprite)
        {
            unMaskImage.sprite = sprite;
        }

        public void SetArrowActive(bool active)
        {
            unmaskArrow.gameObject.SetActive(active);
        }

        public void SetTargetArrow(Transform target, bool isFlip = false, float offset = 0f)
        {
            // unmaskArrow.FitTo(target);
            var rt = unmaskArrow.transform as RectTransform;

            // Debug.Log($"{target.position}, {rt.rect.height}, {target.rect.height/2}, {target.sizeDelta.y/2}");
            // rt.pivot = target.pivot;
            rt.position = target.position;
            rt.localPosition += (rt.rect.height / 2 + offset) * (isFlip ? Vector3.up : Vector3.down);
            rt.rotation = target.rotation;
            if (isFlip)
            {
                arrowAnimator.SetTrigger(Under);
            }

            // var s1 = target.lossyScale;
            // var s2 = rt.parent.lossyScale;
            // rt.localScale = new Vector3(s1.x / s2.x, s1.y / s2.y, s1.z / s2.z);
            // rt.sizeDelta = target.rect.size;
            rt.anchorMax = rt.anchorMin = new Vector2(0.5f, 0.5f);
        }
        
        public void SetTargetArrow(RectTransform target, bool isFlip = false, float offset = 0f)
        {
            // unmaskArrow.FitTo(target);
            var rt = unmaskArrow.transform as RectTransform;

            // Debug.Log($"{target.position}, {rt.rect.height}, {target.rect.height/2}, {target.sizeDelta.y/2}");
            rt.pivot = target.pivot;
            rt.position = target.position;
            rt.localPosition += (rt.rect.height / 2 + target.rect.height / 2 + offset) * (isFlip ? Vector3.up : Vector3.down);
            rt.rotation = target.rotation;
            if (isFlip)
            {
                arrowAnimator.SetTrigger(Under);
            }

            var s1 = target.lossyScale;
            var s2 = rt.parent.lossyScale;
            rt.localScale = new Vector3(s1.x / s2.x, s1.y / s2.y, s1.z / s2.z);
            // rt.sizeDelta = target.rect.size;
            rt.anchorMax = rt.anchorMin = new Vector2(0.5f, 0.5f);
        }

        public void SetBGAlpha(float a)
        {
            backgroundImage.color = backgroundImage.color.SetA(a);
        }
    }
}