using System;
using Assets.Source.Content.Tweens;
using Assets.Source.UI;
using DG.Tweening;
using UnityEngine;

namespace Assets.Source.Content.UI.Components
{
    public class UIAnimMove : UIAnimation
    {
        public RectTransform RectTransform;
        public UITweenDataMove Data;

        public Vector2 From;
        public Vector2 To;

        public bool CustomMode;
        public float CustomDurationIn = -1;
        public float CustomDurationOut = -1;
        public AnimationCurve CustomCurveIn = AnimationCurve.EaseInOut(0, 0, 1, 1);
        public AnimationCurve CustomCurveOut = AnimationCurve.EaseInOut(0, 0, 1, 1);

        private Vector2 _defaultAnchorPos;
        private Tween _tween;

        void Reset()
        {
            RectTransform = GetComponent<RectTransform>();
        }

        protected override void VAwake()
        {
            base.VAwake();
            _defaultAnchorPos = RectTransform.anchoredPosition;
        }
        
        protected override void HandleTrigger(UIAnimationTrigger trigger)
        {
            _tween?.Kill();

            var durationIn = Data?.DurationIn;
            var durationOut = Data?.DurationOut;
            var curveIn = Data?.CurveIn;
            var curveOut = Data?.CurveOut;

            if (CustomMode)
            {
                durationIn = CustomDurationIn;
                durationOut = CustomDurationOut;
                curveIn = CustomCurveIn;
                curveOut = CustomCurveOut;
            }

            switch (trigger)
            {
                case UIAnimationTrigger.Open:
                    RectTransform.anchoredPosition = From;
                    _tween = RectTransform.DOAnchorPos(_defaultAnchorPos, durationIn.Value).SetEase(curveIn);
                    break;
                case UIAnimationTrigger.Close:
                    _tween = RectTransform.DOAnchorPos(To, durationOut.Value).SetEase(curveOut);
                    break;
            }

            _tween.onComplete = () => _tween = null;
        }

        public override void EndInstantly()
        {
            _tween?.Complete();
        }

        public override float GetInDuration()
        {
            return CustomMode ? CustomDurationIn : Data.DurationIn;
        }

        public override float GetOutDuration()
        {
            return CustomMode ? CustomDurationOut : Data.DurationOut;
        }
    }
}
