using DG.Tweening;
using System;
using UnityEngine;
using XGame.Framework.Interfaces;
using XGame.Framework.Time;

namespace FL.Battle.Actions
{
    /// <summary>
    /// MoveLineAction的参数
    /// </summary>
    public struct MoveActionArgs
    {
        public Vector3 from;
        public Vector3 to;
        /// <summary>
        /// 单位:毫秒
        /// </summary>
        public int duration;
        /// <summary>
        /// 延迟，单位: 毫秒
        /// </summary>
        public int delay;
        public Ease ease;
        public Action<Vector3> onUpdate;
        public Action onComplete;
    }
    /// <summary>
    /// 直线移动
    /// Dotween.DOMove
    /// </summary>
    public class MoveLineAction : IAction, IPauseable, ITimeScalable
    {
        public MoveActionArgs args;
        private Tween _tween;
        private bool _paused;
        float ITimeScalable.TimeScale
        {
            get => _tween?.timeScale ?? 1;
            set
            {
                if (_tween == null)
                {
                    return;
                }
                _tween.timeScale = value;
            }
        }
        void IReference.Clear()
        {
            args = default;
            _tween?.Kill();
            _tween = null;
            _paused = false;
        }
        public void Start(Transform transform)
        {
            transform.position = args.from;
            _tween = transform.DOMove(args.to, args.duration * 0.001f);
            if (args.delay > 0)
            {
                _tween.SetDelay(args.delay * 0.001f);
            }
            _tween.SetEase(args.ease == Ease.Unset ? Ease.Linear : args.ease);
            if (args.onUpdate != null)
            {
                _tween.onUpdate += () =>
                {
                    args.onUpdate.SafeInvoke(transform.position);
                };
            }
            _tween.onComplete += () =>
            {
                var callback = args.onComplete;
                _tween = null;
                args = default;
                callback.SafeInvoke();
            };
        }
        void IPauseable.Pause()
        {
            if (_tween == null || _paused)
            {
                return;
            }
            _paused = true;
            _tween.Pause();
        }
        void IPauseable.Resume()
        {
            if (_paused)
            {
                _paused = false;
                _tween?.Play();
            }
        }
    }
}
