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

namespace skyscraper8.UI.MonoGame.Bridge;

public class FpsCounterWindow : ImGuiRenderable, GameObject
{
    public FpsCounterWindow()
    {
        open = true;
    }
    public void Dispose()
    {
    }

    public void Update()
    {
    }

    private bool open;
    public void Render()
    {
        ImGui.Begin("FPS Counter", ref open);
        if (!samplingDone)
        {
            ImGui.Text("Sampling...");
        }
        else
        {
            ImGui.Text(String.Format("FPS: {0}", lastCallsPerSecond));
        }

        ImGui.End();
    }

    public bool WasClosed()
    {
        return !open;
    }

    private bool samplingDone;
    private int secondsPassed;
    private DateTime lastSeconds;
    private int thisCallsPerSecond;
    private int lastCallsPerSecond;
    public void Update(GameTime gameTime, GraphicsDevice graphicsDevice)
    {
        thisCallsPerSecond++;
        DateTime currentSeconds = DateTime.Now;
        if (lastSeconds.Second != currentSeconds.Second)
        {
            lastCallsPerSecond = thisCallsPerSecond;
            secondsPassed++;
            lastSeconds = currentSeconds;
            thisCallsPerSecond = 0;
            if (samplingDone)
            {
                OnSampleAvailable?.Invoke(currentSeconds, lastCallsPerSecond);
            }
        }

        if (secondsPassed >= 2)
        {
            samplingDone = true;
        }
    }

    public void Draw(GameTime gameTime, SpriteBatch spriteBatch, Rectangle windowBounds)
    {
        
    }

    public delegate void SampleAvailable(DateTime time, int fps);
    public event SampleAvailable OnSampleAvailable;
}