Minecraft-Console-Client/MinecraftClient/Protocol/Handlers/StructuredComponents/Core/SubComponentRegistry.cs

40 lines
1.5 KiB
C#
Raw Normal View History

2024-09-01 20:42:39 +02:00
using System;
using System.Collections.Generic;
2024-09-11 19:12:31 +02:00
using System.Reflection;
2024-09-01 20:42:39 +02:00
namespace MinecraftClient.Protocol.Handlers.StructuredComponents.Core;
public abstract class SubComponentRegistry(DataTypes dataTypes)
{
private readonly Dictionary<string, Type> _subComponentParsers = new();
protected void RegisterSubComponent<T>(string name) where T : SubComponent
{
if (_subComponentParsers.TryGetValue(name, out _))
2024-09-01 20:42:39 +02:00
throw new Exception($"Sub component {name} already registered!");
_subComponentParsers.Add(name, typeof(T));
}
protected void ReplaceSubComponent<T>(string name) where T : SubComponent
{
_subComponentParsers[name] = typeof(T);
}
2024-09-01 20:42:39 +02:00
public SubComponent ParseSubComponent(string name, Queue<byte> data)
{
if (!_subComponentParsers.TryGetValue(name, out var subComponentParserType))
2024-09-01 20:42:39 +02:00
throw new Exception($"Sub component {name} not registered!");
var instance = Activator.CreateInstance(subComponentParserType, dataTypes, this) as SubComponent ??
2024-09-01 20:42:39 +02:00
throw new InvalidOperationException($"Could not create instance of a sub component parser type: {subComponentParserType.Name}");
2024-09-11 19:12:31 +02:00
var parseMethod = instance.GetType().GetMethod("Parse", BindingFlags.Instance | BindingFlags.NonPublic);
if (parseMethod is null)
2024-09-11 19:12:31 +02:00
throw new InvalidOperationException($"Sub component parser type {subComponentParserType.Name} does not have a Parse method.");
2024-09-11 19:12:31 +02:00
parseMethod.Invoke(instance, new object[] { data });
2024-09-01 20:42:39 +02:00
return instance;
}
}