using Sandbox;
using System;

namespace VeloX;

public partial class WheelPowertrain : PowertrainComponent
{
	protected override void OnAwake()
	{
		base.OnAwake();
		Name ??= Wheel.ToString();
	}
	[Property] public VeloXWheel Wheel { get; set; }

	protected override void OnStart()
	{
		_initialRollingResistance = Wheel.RollingResistanceTorque;
	}
	private float _initialRollingResistance;

	public override float QueryAngularVelocity( float angularVelocity, float dt )
	{
		InputAngularVelocity = OutputAngularVelocity = Wheel.AngularVelocity;

		return OutputAngularVelocity;
	}

	public override float QueryInertia()
	{
		// Calculate the base inertia of the wheel and scale it by the inverse of the dt.
		float dtScale = Math.Clamp( Time.Delta, 0.01f, 0.05f ) / 0.005f;
		float radius = Wheel.Radius;
		return 0.5f * Wheel.Mass * radius * radius * dtScale;
	}

	public void ApplyRollingResistanceMultiplier( float multiplier )
	{

		Wheel.RollingResistanceTorque = _initialRollingResistance * multiplier;
	}
	public override float ForwardStep( float torque, float inertiaSum, float dt )
	{
		InputTorque = torque;
		InputInertia = inertiaSum;

		OutputTorque = InputTorque;
		OutputInertia = Wheel.BaseInertia + inertiaSum;

		Wheel.DriveTorque = OutputTorque;
		Wheel.Inertia = OutputInertia;

		Wheel.AutoSimulate = false;
		Wheel.StepPhys( Controller, dt );
		
		return Math.Abs( Wheel.CounterTorque );
	}

	protected override void DrawGizmos()
	{

		if ( !Gizmo.IsSelected )
			return;
		Gizmo.Transform = Wheel.WorldTransform;
		Wheel?.GizmoDraw();

	}
}
