using System.Threading;
using System.Threading.Tasks;
using Godot;
using GTweens.Builders;
using GTweens.Easings;
using GTweensGodot.Extensions;

namespace Cirno.Scripts.Resources.Events;

[GlobalClass]
public partial class MovePlayerEvent : EventResource
{
    [Export]
    public Vector2 RelativeTargetPosition = Vector2.Zero;

    [Export]
    public float MovementTime = 1f;

    [Export]
    public Tween.EaseType EaseType = Tween.EaseType.InOut;
    
    [Export]
    public Tween.TransitionType TransitionType = Tween.TransitionType.Linear;
    
    [Export] public GTweens.Easings.Easing GTweenEasing { get; private set; } = Easing.Linear;
    
    private bool _isComplete = false;
    
    private GameManager _gameManager;

    public override void Init(Node2D parent)
    {
        _gameManager = parent.GetGameManager();
    }

    public override void Start(Node2D parentNode)
    {
        _isComplete = false;
        _ = MovePlayer();
    }
    
    protected async Task MovePlayer()
    {
        GameManager.Instance.Player.SetState(PlayerState.Cutscene);
        //_gameManager.Player.RequestMovementDisable(true);
        
        var gtween = GTweenSequenceBuilder.New()
            .Append(_gameManager.Player.MainObject.TweenGlobalPosition(
                        _gameManager.Player.MainObject.GlobalPosition + RelativeTargetPosition, MovementTime)
                    .SetEasing(GTweenEasing)
                //.
            )
            .Build();
        
        await gtween.PlayAsync(CancellationToken.None);
        
        // Tween tween = _gameManager.GetTree().CreateTween();
        // tween.SetEase(EaseType);
        // tween.SetTrans(TransitionType);
        // tween.TweenProperty(_gameManager.Player, "global_position", _gameManager.Player.GlobalPosition + RelativeTargetPosition, MovementTime);
        //
        // // Wait for the tween to finish
        // await ToSignal(tween, "finished");
        
        GameManager.Instance.Player.SetState(PlayerState.Active);
        //_gameManager.Player.RequestMovementDisable(false);

        _isComplete = true;
    }
    
    public override void UpdateEvent(double delta) { }
    
    public override bool IsComplete()
    {
        return _isComplete;
    }
}