using System;
using UnityEngine;

namespace Radium.PingPongPatch.Managers;

public sealed class PingPongManager(IntPtr ptr) : MonoBehaviour(ptr)
{
    private PerformanceCounters performanceCounters;

    private void Awake()
        => performanceCounters = FindObjectOfType<PerformanceCounters>();

    private void OnGUI()
    {
        if (performanceCounters == null)
        {
            performanceCounters = FindObjectOfType<PerformanceCounters>();
            if (performanceCounters == null)
                return;
        }

        var x = 0f;

        if (Plugin.ShowFPS.Value)
        {
            var fps = performanceCounters.JLBFLIBDIIN;

            var text = $"FPS: {fps:F1}";
            var size = GUI.skin.label.CalcSize(new GUIContent(text));

            GUI.Box(new Rect(x, 0, size.x + 12, 22), string.Empty);
            GUI.Label(new Rect(x + 6, 1, size.x, 20), text);

            x += size.x + 12;
        }

        if (Plugin.ShowPing.Value)
        {
            var ping = performanceCounters.GABBHJIKILN;

            var text = $"Ping: {ping}ms";
            var size = GUI.skin.label.CalcSize(new GUIContent(text));

            var t = Mathf.Clamp01(ping / 270f);
            var oldColor = GUI.contentColor;

            GUI.contentColor = t < 0.5f ? Color.Lerp(Color.green, Color.yellow, t * 2f) : Color.Lerp(Color.yellow, Color.red, (t - 0.5f) * 2f);

            GUI.Box(new Rect(x, 0, size.x + 12, 22), string.Empty);
            GUI.Label(new Rect(x + 6, 1, size.x, 20), text);

            GUI.contentColor = oldColor;
        }
    }
}