using Sandbox;
using System;
using System.Diagnostics;
using System.Linq;
namespace VeloX;

internal sealed class WheelManager : GameObjectSystem
{


	public WheelManager( Scene scene ) : base( scene )
	{
		Listen( Stage.StartFixedUpdate, -99, UpdateWheels, "UpdateWheels" );
		Listen( Stage.StartFixedUpdate, -100, UpdateEngine, "UpdateEngine" );
	}

	private void UpdateWheels()
	{
		if ( !Game.IsPlaying || Scene.IsEditor )
			return;
		//Stopwatch sw = Stopwatch.StartNew();

		var wheels = Scene.GetAll<VeloXWheel>();
		if ( !wheels.Any() ) return;

		var timeDelta = Time.Delta;
		Sandbox.Utility.Parallel.ForEach( wheels, item =>
		{
			if ( !item.IsProxy )
				item.DoPhysics( timeDelta );
		} );
		foreach ( var wheel in wheels )
			wheel.UpdateForce();

		//sw.Stop();

		//DebugOverlaySystem.Current.ScreenText( new Vector2( 120, 30 ), $"Wheel Sim: {sw.Elapsed.TotalMilliseconds,6:F2} ms", 24 );
	}
	private void UpdateEngine()
	{
		if ( !Game.IsPlaying || Scene.IsEditor )
			return;
		//Stopwatch sw = Stopwatch.StartNew();

		var engines = Scene.GetAll<Engine>();
		if ( !engines.Any() ) return;

		var timeDelta = Time.Delta;
		Sandbox.Utility.Parallel.ForEach( engines, item =>
		{
			if ( !item.IsProxy )
				item.UpdateEngine( timeDelta );
		} );
		//sw.Stop();

		//DebugOverlaySystem.Current.ScreenText( new Vector2( 120, 54 ), $"Engine Sim: {sw.Elapsed.TotalMilliseconds,6:F2} ms", 24 );
	}
}
