using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace skyscraper8.UI.MonoGame.Bridge;

public class IqWindow : TextureDisplayWindow
{
    public IqWindow(GraphicsDevice graphicsDevice, ImGuiRenderer renderer, string name = "IQ", bool closeable = false) 
        : base(renderer, new Texture2D(graphicsDevice,256,256), name, closeable)
    {
        sampleQueue = new Queue<Tuple<byte, byte>>();
        colorBuffer = new Color[256 * 256];
        zBuffer = new byte[256 * 256];
        _texture.GetData(colorBuffer);
        Array.Fill(colorBuffer, Color.Transparent);
    }

    private Queue<Tuple<byte, byte>> sampleQueue;

    public void EnqueueSample(byte i, byte q)
    {
        sampleQueue.Enqueue(new Tuple<byte, byte>(i, q));
    }

    private byte[] zBuffer;
    private Color[] colorBuffer;
    public override void Update()
    {
        while (sampleQueue.Count > 0)
        {
            Tuple<byte, byte> dequeue = sampleQueue.Dequeue();
            int offset = dequeue.Item2 * 256;
            offset += dequeue.Item1;
            byte z = zBuffer[offset]++;
            colorBuffer[offset] = new Color(z, 0, 255 - z, 255);
        }
        
        _texture.SetData(colorBuffer);
        base.Update();
    }
}