using System.Reflection;
using PkmnLib.Static.Utils;
namespace PkmnLib.Dynamic.ScriptHandling.Registry;
///
/// Extension methods for scripts.
///
public static class ScriptUtils
{
private static readonly Dictionary Cache = new();
///
/// Resolve name from the of the given script.
///
public static StringKey ResolveName(this Script script) => ResolveName(script.GetType());
///
/// Resolve name from the of the given type.
///
public static StringKey ResolveName() where T : Script => ResolveName(typeof(T));
///
/// Resolve name from the of the given type.
///
public static StringKey ResolveName(Type type) => GetFromCacheOrAdd(type).name;
///
/// Resolve category from the of the given script.
///
public static ScriptCategory ResolveCategory(this Script script) => ResolveCategory(script.GetType());
///
/// Resolve category from the of the given script.
///
public static ScriptCategory ResolveCategory() where T : Script => ResolveCategory(typeof(T));
///
/// Resolve category from the of the given type.
///
public static ScriptCategory ResolveCategory(Type type) => GetFromCacheOrAdd(type).category;
private static (ScriptCategory category, StringKey name) GetFromCacheOrAdd(Type type)
{
if (Cache.TryGetValue(type, out var key))
return key;
var scriptAttr = type.GetCustomAttribute();
if (scriptAttr == null)
throw new InvalidOperationException($"Type {type} does not have a {nameof(ScriptAttribute)}.");
return Cache[type] = (scriptAttr.Category, scriptAttr.Name);
}
}