using System.Numerics;
using ImGuiNET;
using Microsoft.Xna.Framework.Graphics;

namespace skyscraper8.UI.MonoGame.Bridge;

public class TextureDisplayWindow : ImGuiRenderable
{
    protected Texture2D _texture;
    protected string _name;
    protected bool open;
    private bool closeable;
    protected ImGuiRenderer _renderer;
    
    public TextureDisplayWindow(ImGuiRenderer renderer, Texture2D texture, string name = null, bool closeable = false)
    {
        if (renderer == null)
            throw new ArgumentNullException(nameof(renderer));
        _renderer = renderer;
        
        this._texture = texture;
        this._name = name;
        if (string.IsNullOrEmpty(name))
        {
            this._name = texture.ToString();
        }

        this.open = true;
        this.closeable = closeable;
    }

    private bool bound;
    private IntPtr _texturePointer;
    protected System.Numerics.Vector2 windowSize;
    public virtual void Update()
    {
        if (_texture == null)
            return;

        if (!bound)
        {
            _texturePointer = _renderer.BindTexture(_texture);
            windowSize = new Vector2(_texture.Width, _texture.Height);
            bound = true;
        }
    }

    public void Render()
    {
        if (!bound)
            return;

        ImGui.SetNextWindowSize(windowSize);
        if (closeable)
            ImGui.Begin(_name, ref open);
        else
            ImGui.Begin(_name);

        ImGui.Image(_texturePointer, windowSize);

        ImGui.End();
    }

    public bool WasClosed()
    {
        return !open;
    }

    public void Dispose()
    {
        if (bound)
        {
            _renderer.UnbindTexture(_texturePointer);
            bound = false;
        }

        _texture.Dispose();
    }
}