using HarmonyLib;
using UnityEngine;

namespace MuzikaGromche.Via;

class ViaBehaviour : MonoBehaviour
{
    static ViaBehaviour? instance = null;

    public static ViaBehaviour Instance
    {
        get
        {
            if (instance == null)
            {
                var go = new GameObject("MuzikaGromche_ViaBehaviour", [
                    typeof(ViaBehaviour),
                ])
                {
                    hideFlags = HideFlags.HideAndDontSave
                };
                DontDestroyOnLoad(go);
                instance = go.GetComponent<ViaBehaviour>();
            }
            return instance;
        }
    }

    DevicePool<ViaDeviceDelegate> devicePool = null!;
    DevicePoolLightshow<ViaDeviceDelegate> lightshow = null!;

    void Awake()
    {
        devicePool = new DevicePool<ViaDeviceDelegate>(new FrameworkDeviceFactory());
        lightshow = new DevicePoolLightshow<ViaDeviceDelegate>(devicePool);
    }

    void OnDestroy()
    {
        devicePool.Dispose();
    }

    public void SetColor(Color color)
    {
        Color.RGBToHSV(color, out var hue, out var saturation, out var value);

        var h = (byte)Mathf.RoundToInt(hue * 255);
        var s = (byte)Mathf.RoundToInt(saturation * 255);
        var v = (byte)Mathf.RoundToInt(value * 255);

        lightshow.SetColor(h, s, v);
    }

    public void Restore()
    {
        devicePool.Restore();
    }

    public void Flicker()
    {
        Animations.Flicker(lightshow);
    }
}

[HarmonyPatch(typeof(RoundManager))]
static class ViaFlickerLightsPatch
{
    [HarmonyPatch(nameof(RoundManager.FlickerLights))]
    [HarmonyPrefix]
    static void OnFlickerLights(RoundManager __instance)
    {
        var _ = __instance;
        ViaBehaviour.Instance.Flicker();
    }
}
