using Editor;
using Editor.Assets;
using Editor.Inspectors;
using Sandbox;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace VeloX;

[AssetPreview( "tire" )]
class TirePresetPreview : AssetPreview
{
	public override bool IsAnimatedPreview => false;
	[Range( 0.01f, 1 )] private float Zoom { get; set; } = 1;

	public override Widget CreateToolbar()
	{
		var info = new IconButton( "settings" );
		info.Layout = Layout.Row();
		info.MinimumSize = 16;
		info.MouseLeftPress = () => OpenSettings( info );
		return info;
	}
	public void OpenSettings( Widget parent )
	{
		var popup = new PopupWidget( parent )
		{
			IsPopup = true,
			Layout = Layout.Column()
		};

		popup.Layout.Margin = 16;

		var ps = new ControlSheet();

		ps.AddProperty( this, x => x.Zoom );

		popup.Layout.Add( ps );
		popup.MaximumWidth = 300;
		popup.Show();
		popup.Position = parent.ScreenRect.TopRight - popup.Size;
		popup.ConstrainToScreen();

	}

	public override async Task InitializeAsset()
	{
		await Task.Yield();

		using ( Scene.Push() )
		{
			PrimaryObject = new( true )
			{
				WorldTransform = Transform.Zero
			};

			var spriteRenderer = PrimaryObject.AddComponent<SpriteRenderer>();

			var bitmap = new Bitmap( 512, 512 );
			var tire = Asset.LoadResource<TirePreset>();
			Draw( bitmap, tire );

			spriteRenderer.Sprite = new() { Animations = [new() { Frames = [new() { Texture = bitmap.ToTexture() }] },] }; // Set the texture on the renderer
			spriteRenderer.Size = 512;

		}

		return;
	}
	public override void UpdateScene( float cycle, float timeStep )
	{
		base.UpdateScene( cycle, timeStep );

		Camera.Orthographic = true;
		Camera.OrthographicHeight = 512;
		Camera.WorldPosition = Vector3.Backward * 512;
		Camera.WorldRotation = Rotation.LookAt( Vector3.Forward );


		var bitmap = new Bitmap( 512, 512 );
		var tire = Asset.LoadResource<TirePreset>();
		Draw( bitmap, tire );

		PrimaryObject.Components.Get<SpriteRenderer>().Sprite = new() { Animations = [new() { Frames = [new() { Texture = bitmap.ToTexture() }] },] }; // Set the texture on the renderer
		PrimaryObject.Components.Get<SpriteRenderer>().Size = 512;


	}

	private readonly List<Vector2> pointCache = [];

	public TirePresetPreview( Asset asset ) : base( asset )
	{
	}

	private void DrawPacejka( Bitmap bitmap, TirePreset tire )
	{

		var width = bitmap.Width;
		var height = bitmap.Height;


		{ // draw lateral line
			pointCache.Clear();

			bitmap.SetPen( Color.Red, 1 );

			for ( float x = 0; x <= 1; x += 0.01f )
			{
				float val = tire.Evaluate( x ) * Zoom;
				pointCache.Add( new( width * x, height - height * val ) );
			}

			bitmap.DrawLines( pointCache.ToArray() );
		}
		pointCache.Clear();
	}
	private void Draw( Bitmap bitmap, TirePreset tire )
	{
		bitmap.Clear( Color.Black );
		bitmap.SetAntialias( true );
		DrawPacejka( bitmap, tire );
	}
}
