using DG.Tweening;
using System;
using UnityEngine;
using XGame.Framework.Components;
using XGame.Framework.Map;

namespace FL.Battle
{
    public interface IMoveContext
    {
        Transform OwnerTr { get; }
    }
    /// <summary>
    /// ÒÆ¶¯²ÎÊý
    /// </summary>
    public struct MoveArgs
    {
        public Vector3 target;
        public float speed;
        public Ease ease;
        public Action callback;
    }
    public class MoveComponent : Component<IMoveContext>, IParallelTarget
    {
        public override int Order => 0;

        private Tween _tween;
        public Vector3 MoveDir { get; private set; }
        public bool IsMoving =>  _tween != null;

        Vector3 IParallelTarget.Position => Context.OwnerTr.position;

        public void MoveTo(MoveArgs args)
        {
            var position = Context.OwnerTr.localPosition;
            var duration = Mathf.Abs(args.target.y - position.y) / args.speed;
            MoveDir = Vector3.Normalize(args.target - position);
            var tween = Context.OwnerTr.DOLocalMoveY(args.target.y, duration);
            _tween = tween;
            var ease = args.ease == Ease.Unset ? Ease.Linear : args.ease;
            tween.SetEase(ease);
            tween.onComplete += () =>
            {
                _tween = null;
                MoveDir = Vector3.zero;
                args.callback?.Invoke();
            };
        }
        public void StopMove()
        {
            _tween?.Kill();
            _tween = null;
            MoveDir = Vector3.zero;
        }
        protected override void OnDispose()
        {
            StopMove();
        }
    }
}
