using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Echo.UserInterface.Backend;
using ScottPlot;
using SDL2;
using SkiaSharp;
using skyscraper8.UI.ImGuiForms;
using testdrid.SdlWrapper;

namespace skyscraper8.UI.ImGui.Forms
{
	internal class SdlScottPlotWindow : SdlWindow, IDisposable
	{
		protected readonly Plot _plot;
		private readonly SKBitmap _skBitmap;
		private readonly SKCanvas _skCanvas;

		public SdlScottPlotWindow(ImGuiDevice imGuiDevice, Plot plot, int width, int height, string title)
			: base(imGuiDevice, width, height, title)
		{
			this._plot = plot;
			this._skBitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Bgra8888));
			this._skCanvas = new SKCanvas(_skBitmap);
		}

		private byte[] tempBuffer;
		private int dataLength;
		protected override void RenderInternal(Texture surface)
		{
			BeforeRender();
			_plot.Render(_skCanvas, (int)this._size.X, (int)this._size.Y);

			nint data0 = surface.GetData0();
			nint pixels = _skBitmap.GetPixels();

			if (dataLength == 0)
			{
				dataLength = _skBitmap.ByteCount;
				tempBuffer = new byte[dataLength];
			}

			Marshal.Copy(pixels, tempBuffer, 0, dataLength);
			Marshal.Copy(tempBuffer, 0, data0, dataLength);

		}

		protected virtual void BeforeRender()
		{

		}

		public void Dispose()
		{
			_plot.Dispose();
			_skBitmap.Dispose();
			_skCanvas.Dispose();
			_texture.Dispose();
		}
	}
}
