using Cirno.Scripts.Actors;
using Cirno.Scripts.AttackPatterns;
using Godot;

namespace Cirno.Scripts.Resources;

[GlobalClass]
[Tool]
public partial class FSMMovementPattern : AttackPattern
{
    [Export] private Vector2 relativeTargetPosition;
    [Export] private float moveDuration = 2f;
    [Export] private Tween.TransitionType transitionType = Tween.TransitionType.Linear;
    [Export] private Tween.EaseType easeType = Tween.EaseType.InOut;

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

    public class FSMMovementPatternMachine(FSMMovementPattern pattern, Node parent) : IPatternMachine
    {
        public Node Parent => parent;
        
        private Tween tween;
        private bool isComplete = false;

        protected IScriptHost Boss;
    
        public void Start()
        {
            if (parent is not IScriptHost boss)
                return;
        
            Boss = boss;
            tween = Parent.CreateTween();
            isComplete = false;

            if (parent is not Node2D parent2d)
            {
                return;
            }
            
            Vector2 targetPosition = (Boss?.HomePosition ?? parent2d.GlobalPosition) + pattern.relativeTargetPosition;
        
            boss.ChangeSpriteDirection(-(parent2d.GlobalPosition - targetPosition));
            tween.TweenProperty(parent2d, "global_position", targetPosition, pattern.moveDuration)
                .SetTrans(pattern.transitionType)
                .SetEase(pattern.easeType)
                .Finished += () =>
            {
                isComplete = true;
                boss.ChangeSpriteDirection(Vector2.Zero);
            };
        }

        public void UpdatePattern(double delta) { }

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