using Sandbox;
using System;

namespace VeloX;


[AssetType( Name = "Wheel Friction", Extension = "tire", Category = "VeloX" )]
public class TirePreset : GameResource
{
	public static TirePreset Default { get; } = ResourceLibrary.Get<TirePreset>( "frictions/default.tire" );

	private float peakSlip = -1;

	[Property] public float B { get; set; } = 10.86f;
	[Property] public float C { get; set; } = 2.15f;
	[Property] public float D { get; set; } = 0.933f;
	[Property] public float E { get; set; } = 0.992f;

	public float GetPeakSlip()
	{
		if ( peakSlip == -1 )
			peakSlip = CalcPeakSlip();

		return peakSlip;
	}


	public float Evaluate( float t ) => D * MathF.Sin( C * MathF.Atan( B * t - E * (B * t - MathF.Atan( B * t )) ) );

	private float CalcPeakSlip()
	{
		float peakSlip = -1;
		float yMax = 0;

		for ( float i = 0; i < 1f; i += 0.01f )
		{
			float y = Evaluate( i );
			if ( y > yMax )
			{
				yMax = y;
				peakSlip = i;
			}
		}

		return peakSlip;
	}

}
