using Godot;

public partial class PlayerWallGrab : State {
    private Player player;

    private float wallDirection;

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

    public override void Enter() {
        player.StateLabel?.Text = Name;
        player.InParachute = false;
        
        Vector2 desiredPos = new (
            (player.WallCastLow.GetCollisionPoint().Snapped(new Vector2(4, 4)) + new Vector2(-2 * player.MoveDir.X, 0)).X,
            player.GlobalPosition.Y);
        var posTween = CreateTween().SetTrans(Tween.TransitionType.Sine);
        posTween.TweenProperty(player, "global_position", desiredPos, 0.05);
        wallDirection = player.MoveDir.X;
    }

    public override void PhysicsUpdate(double delta) {
        var floatDelta = (float)delta;
        player.Velocity = new (0.0f, player.Velocity.Y);
        if (player.MoveDir.X != 0.0) {
            if (!player.WallCastLow.IsColliding() ||
                !player.WallCastMid.IsColliding() ||
                !player.WallCastTop.IsColliding()) {
                EmitSignal(SignalName.Transitioned, this, "PlayerAirborne");
            }
        }

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

        if (Input.IsActionJustPressed("jump")) {
            player.WallCastTop?.Enabled = false;
            player.WallCastMid?.Enabled = false;
            player.WallCastLow?.Enabled = false;
            player.WallCastDelayTimer.Start();
            EmitSignal(SignalName.Transitioned, this, "PlayerAirborne");
            player.Velocity = new (player.Velocity.X, player.Jump * 0.85f);
            if (wallDirection > 0) {
                player.Velocity = new (-player.WallJump, player.Velocity.Y);
            }
            else {
                player.Velocity = new (player.WallJump, player.Velocity.Y);
            }
        }
    }
}
