using Godot;

public partial class PlayerAirborn : State {
    private Player player;

    public override void _Ready() {
        player = GetNode<Player>("../..");
    }

    public override void Enter() {
        GD.Print("airborn");
        player.StateLabel?.Text = Name;
        player.InParachute = false;
        player.AnimStateMachine?.Travel("Airborne");
    }

    public override void PhysicsUpdate(double delta) {
        var floatDelta = (float)delta;
        if (player.IsOnFloor()) {
            EmitSignal(SignalName.Transitioned, this, "PlayerGrounded");
        }

        if (player.MoveDir.X != 0) {
            player.Velocity = new(
                Mathf.MoveToward(player.Velocity.X, player.MoveDir.X * player.Speed, player.Acceleration),
                player.Velocity.Y);
        }
        else {
            player.Velocity = new(
                Mathf.MoveToward(player.Velocity.X, 0.0f, player.AirFriction),
                player.Velocity.Y);
        }

        if (player.Velocity.Y >= 0) {
            player.Velocity = new(
                player.Velocity.X,
                player.Velocity.Y + player.Gravity * floatDelta * player.FallMod);
        }
        else {
            player.Velocity = new(
                player.Velocity.X,
                player.Velocity.Y + player.Gravity * floatDelta);
        }

        var wcl = player.WallCastLow != null && player.WallCastLow.IsColliding();
        var wcm = player.WallCastMid != null && player.WallCastLow.IsColliding();
        var wct = player.WallCastTop != null && player.WallCastTop.IsColliding();
        if (wcl && wcm && wct) {
            EmitSignal(SignalName.Transitioned, this, "PlayerWallGrab");
        }

        if (Input.IsActionJustPressed("jump") && player.CanCoyoteJump) {
            player.Velocity = new(player.Velocity.X, player.Jump);
        }

        LedgeLogic();

        player.LastVelocityY = player.Velocity.Y;
    }

    private void LedgeLogic() {
        if (player.IsOnFloor() || player.Velocity.Y <= -30 || player.MoveDir == Vector2.Zero) {
            return;
        }

        if (!player.WallCastMid.IsColliding() || player.WallCastTop.IsColliding()) {
            return;
        }

        var desiredPos = player.WallCastMid.GetCollisionPoint().Snapped(new Vector2(4, 4)) + new Vector2(-2 * player.MoveDir.X, -1);
        var posTween = CreateTween().SetTrans(Tween.TransitionType.Sine);
        posTween.TweenProperty(player, "global_position", desiredPos, 0.05);

        player.LastVelocityY = 0.0f;
        player.Velocity = new (0.0f, player.LedgeJump);
    }
}