using Editor;
using Sandbox;

namespace VeloX;

internal sealed class SimulatedEngineWidget : Widget
{

	public FloatSlider Throttle;
	public FloatSlider RPM;

	public EngineStreamPlayer Player { get; private set; }
	public bool IsPlaying { get; private set; }
	public SimulatedEngineWidget( Widget parent, EngineStream stream ) : base( parent )
	{
		Player = new EngineStreamPlayer( stream );
		Layout = Layout.Column();
		Layout.Alignment = TextFlag.Top;
		Layout.Spacing = 6;
		Layout.Margin = new Sandbox.UI.Margin( 8, 8, 16, 8 );


		var title = new Label( "Simulated Engine" );
		title.SetStyles( "background-color:rgba(29, 62, 81, 200);" );
		title.Alignment = TextFlag.CenterHorizontally;
		title.Margin = 8;
		var startButton = new Button( "Toggle Engine" )
		{
			Clicked = () =>
			{
				IsPlaying = !IsPlaying;

			}
		};
		Layout.Add( title );
		Layout.Add( startButton );

		var rpmTitle = new Label( "RPM" );
		Layout.Add( rpmTitle );

		RPM = new FloatSlider( rpmTitle )
		{
			Maximum = 1,
			Value = 0.5f
		};
		Layout.Add( RPM );

		var throttleTitle = new Label( "Throttle" );
		Layout.Add( throttleTitle );

		Throttle = new FloatSlider( throttleTitle )
		{
			Maximum = 1,
			Value = 0.5f
		};
		Layout.Add( Throttle );
	}

	[EditorEvent.Hotload]
	internal void Dispose()
	{
		Player.Dispose();
	}
	protected override void OnClosed()
	{
		base.OnClosed();
		Dispose();
	}
	public override void OnDestroyed()
	{
		base.OnDestroyed();
		Dispose();
	}
	bool IsRedlining;

	[EditorEvent.Frame]
	public void OnFrame()
	{
		if ( Player is null || !Player.Stream.IsValid() )
			return;
		Player.EngineState = IsPlaying ? EngineState.Running : EngineState.Off;

		Player.Throttle = Throttle.Value;
		Player.RPMPercent = RPM.Value;
		IsRedlining = RPM.Value == 1 && !IsRedlining;
		Player.IsRedlining = IsRedlining;

		Player?.Update( Time.Delta, Vector3.Zero, true );

	}
}
