Files
vpr-mitarbeiterverwaltung/Server/CommandManager.cs
2025-06-05 08:27:40 +02:00

54 lines
1.7 KiB
C#

using System.Net.Sockets;
using System.Reflection;
using System.Text.Json;
using DX86;
using Server.Commands;
namespace Server;
public class CommandManager
{
private readonly Dictionary<string, ICommand> _commands = new();
public CommandManager()
{
LoadCommands();
}
private void LoadCommands()
{
// Get all types implementing ICommand
var commandTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(ICommand).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
foreach (var type in commandTypes)
{
// Create an instance of the command
if (Activator.CreateInstance(type) is ICommand command)
{
// Use the Executor property as the key
_commands[command.Executor] = command;
}
}
}
public void ExecuteCommand(string executor, TcpClient? client = null, TcpServer? clientSocket = null, string cid = "", params string[] args)
{
if (_commands.TryGetValue(executor, out var command))
{
JsonMessage returnMessage = new JsonMessage();
returnMessage.cid = cid;
returnMessage.cmd = command.Exec(args:args, client:client, clientSocket:clientSocket);
string sendClientMessage = JsonSerializer.Serialize(returnMessage);
clientSocket.SendMessageAsync(client:client, message:sendClientMessage+"\n");
//clientSocket.SendMessageAsync(client:client, message:command.Exec(args:args, client:client, clientSocket:clientSocket));
}
else
{
Program.messageSender.Log($"[COMMANDMANAGER] Command '{executor}' not found.");
}
}
}