using Godot;

public partial class PlayerGrounded : State {
	private Player player;
	private Node3D modelRoot;

	public override void _Ready() {
		player = GetNode<Player>("../..");
		modelRoot = GetNode<Node3D>("../../ModelContainer/SubViewportContainer/SubViewport/blockbench_export");
	}

	public override void Enter() {
		player.StateLabel?.Text = Name;
		player.ResetCoyoteTimer();
		player.InParachute = false;
		player.AnimStateMachine?.Travel("Grounded");

		var fall_speed = Mathf.Abs(player.LastVelocityY);
		fall_speed *= 0.0025f;
		if (modelRoot != null) {
			modelRoot.Scale = new (
				modelRoot.Scale.X + fall_speed,
				modelRoot.Scale.Y - fall_speed,
				modelRoot.Scale.Z + fall_speed);

			var fallTween = GetTree().CreateTween();
			fallTween.TweenProperty(
				modelRoot,
				"scale",
				new Vector3(1.0f, 1.0f, 1.0f),
				0.2);
		}


		// if (player.SprintStateMachine) {
		// 	if (move_dir < 0) {
		// 		player.SprintStateMachine.travel("sprint_left");
		// 	}
		// 	else if (move_dir > 0) {
		// 		player.SprintStateMachine.travel("sprint_right");
		// 	}
		// }
	}

	public override void PhysicsUpdate(double delta) {
		if (!player.IsOnFloor()) {
			EmitSignal(SignalName.Transitioned, this, "PlayerAirborne");
		}

		if (player.MoveDir.X != 0) {
			if (Input.IsActionPressed("slow_walk")) {
				player.Velocity = new (
					Mathf.MoveToward(player.Velocity.X, player.MoveDir.X * player.Speed * player.SlowMod, player.Acceleration),
					player.Velocity.Y);
				player.GroundedStateMachine?.Travel("Walk");
			}
			else {
				player.Velocity = new (
					Mathf.MoveToward(player.Velocity.X, player.MoveDir.X * player.Speed, player.Acceleration),
					player.Velocity.Y);
				player.GroundedStateMachine?.Travel("Sprint");

				if (player.MoveDir.X < 0) {
					player.SprintStateMachine?.Travel("sprint_left");
				}
				else if (player.MoveDir.X > 0) {
					player.SprintStateMachine?.Travel("sprint_right");
				}
			}
		}
		else {
			player.Velocity = new (
				Mathf.MoveToward(player.Velocity.X, 0.0f, player.Friction),
				player.Velocity.Y);
			player.GroundedStateMachine?.Travel("Idle");
		}

		if (Input.IsActionJustPressed("jump") && player.IsOnFloor()) {
			player.Velocity = new (player.Velocity.X, player.Jump);
			EmitSignal(SignalName.Transitioned, this, "PlayerAirborne");
		}
	}
}
