using System.Runtime.InteropServices;
using Microsoft.Xna.Framework.Graphics;
using ScottPlot;
using SkiaSharp;

namespace skyscraper8.UI.MonoGame.Bridge;

public class ScottPlotWindow : TextureDisplayWindow
{
    public Plot Plot { get; private set; }
    private SKImageInfo _imageInfo;
    private SKBitmap _bitmap;
    private SKCanvas _canvas;
    
    public ScottPlotWindow(ImGuiRenderer renderer, GraphicsDevice graphicsDevice, Plot plot, int width, int height, string name = null, bool closeable = false)
        : base(renderer, new Texture2D(graphicsDevice,width,height), name, closeable)
    {
        if (renderer == null)
            throw new ArgumentNullException(nameof(renderer));
        
        if (graphicsDevice == null)
            throw new ArgumentNullException(nameof(graphicsDevice));
        
        if (plot == null)
            throw new ArgumentNullException(nameof(plot));
        Plot = plot;

        _imageInfo = new SKImageInfo(width, height, GuessSKColorType(graphicsDevice));
        _bitmap = new SKBitmap(width, height);
        _canvas = new SKCanvas(_bitmap);
    }

    private SKColorType GuessSKColorType(GraphicsDevice graphicsDevice)
    {
        SurfaceFormat xnaSurfaceFormat = graphicsDevice.PresentationParameters.BackBufferFormat;
        switch (xnaSurfaceFormat)
        {
            case SurfaceFormat.Color:
                return SKColorType.Rgba8888;
            default:
                throw new NotImplementedException(xnaSurfaceFormat.ToString());
        }
    }



    private byte[] buffer;
    public override void Update()
    {
        Plot.Render(_canvas, _imageInfo.Width, _imageInfo.Height);

        IntPtr pixelPointer = _bitmap.GetPixels();
        int size = (_bitmap.Width * _bitmap.Height) * 4;
        if (buffer == null)
            buffer = new byte[size];
        Marshal.Copy(pixelPointer, buffer, 0, size);

        _texture.SetData(buffer);
        
        base.Update();
    }
}