using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Utilities;
using Reactor.Utilities;
using Rewired;
namespace MiraAPI.Keybinds;
///
/// Lets you register and manage mod keybinds with conflict checks and rebinding support.
///
public static class KeybindManager
{
///
/// Gets a list of all registered keybinds.
///
public static List Keybinds { get; } = new();
internal static Dictionary VanillaKeybinds { get; set; }
internal static void RewiredInit()
{
try
{
var instance = KeybindUtils.RewiredInputManager!;
foreach (var keybind in KeybindManager.Keybinds)
{
if (instance.userData.actions.ToArray().Any(x => x.name == keybind.Id))
{
Logger.Warning($"Keybind of id {keybind.Id} already exists. Skipping it");
continue;
}
keybind.RewiredInputAction = instance.userData.RegisterModBind(
keybind.Id,
keybind.Name,
keybind.SourcePluginName,
keybind.DefaultKey,
modifiers: keybind.ModifierKeys);
}
}
catch (Exception e)
{
Logger.Error($"Error while registering keybinds in Rewired: {e}");
}
}
///
/// Returns all conflicts where keybinds use the same key.
///
/// A list of pairs of keybinds that conflict.
public static Dictionary> GetConflicts()
{
var conflicts = new Dictionary>();
foreach (var keybind in Keybinds)
{
var all = GetKeybindsForKey(keybind.CurrentKey, true);
if (all.Length > 1)
{
if (!conflicts.TryGetValue(keybind.CurrentKey, out var group))
{
conflicts.Add(keybind.CurrentKey, new List());
group = conflicts[keybind.CurrentKey];
}
if (!group.Contains(keybind))
{
group.Add(keybind);
}
}
}
return conflicts;
}
///
/// Returns all keybinds for a specified keycode.
///
/// The key to look for.
/// /// Should only exlusive keybinds be present.
/// The list of keybinds.
public static MiraKeybind[] GetKeybindsForKey(KeyboardKeyCode keyCode, bool exclusiveCheck = false)
{
var all = new List();
foreach (var keybind in Keybinds)
{
if (keybind.CurrentKey == keyCode && (keybind.Exclusive || !exclusiveCheck))
{
all.Add(keybind);
}
}
return all.ToArray();
}
}