using Cirno.Scripts.Resources;
using Godot;
using GTweens.Builders;
using GTweens.Easings;
using GTweens.Tweens;
using GTweensGodot.Extensions;

namespace Cirno.Scripts.AttackPatterns;

[GlobalClass]
[Tool]
public partial class NodeMovementPattern : AttackPattern
{
    [Export] private Vector2 relativeTargetPosition;
    [Export] private float moveDuration = 2f;
    // [Export] private Tween.TransitionType transitionType = Tween.TransitionType.Linear;
    [Export] public GTweens.Easings.Easing EaseType { get; private set; } = Easing.Linear;

    public override IPatternMachine MakeMachine(Node parent)
    {
        return new NodeMovementPatternMachine(this, parent);
    }

    public class NodeMovementPatternMachine(NodeMovementPattern pattern, Node parent) : IPatternMachine
    {
        public Node Parent => parent;
        
        private GTween _tween;
        private bool isComplete = false;
    
        public void Start()
        {
            if (Parent is not IScriptHost scriptHost)
            {
                GD.PrintErr("Parent was not a script host");
                isComplete = true;
                return;
            }
            
            
            _tween?.Complete();
            
            isComplete = false;

            Vector2 targetPosition = (scriptHost?.HomePosition ?? scriptHost.ParentObject.GlobalPosition) + pattern.relativeTargetPosition;

            _tween = GTweenSequenceBuilder.New()
                .Append(scriptHost.ParentObject.TweenGlobalPosition(targetPosition, pattern.moveDuration))
                .AppendCallback(() =>
                {
                    isComplete = true;
                })
                .Build();

            _tween.SetEasing(pattern.EaseType);
            
            _tween.Play();
            // tween.TweenProperty(Parent, "global_position", targetPosition, pattern.moveDuration)
            //     .SetTrans(pattern.transitionType)
            //     .SetEase(pattern.easeType)
            //     .Finished += () =>
            // {
            //     isComplete = true;
            // };
        }

        public void UpdatePattern(double delta) { }

        public bool IsComplete()
        {
            return isComplete;
        }
    }
}