using System;
using System.Collections.Generic;
using Crysome.Common.Network;
using Crysome.Common.Network.Packets;

namespace Crysome.Client.Network;

public class PacketChannel
{
	public readonly Dictionary<Type, Action<CrysomeClient, IPacket>> Handlers;

	public PacketChannel()
	{
		Handlers = new Dictionary<Type, Action<CrysomeClient, IPacket>>();
	}

	public void HandlePacket(CrysomeClient client, IPacket packet)
	{
		foreach (KeyValuePair<Type, Action<CrysomeClient, IPacket>> handler in Handlers)
		{
			if (handler.Key.Equals(((object)packet).GetType()))
			{
				handler.Value(client, packet);
				break;
			}
		}
	}

	public void RegisterHandler<TPacket>(Action<CrysomeClient, IPacket> handler)
	{
		if (Handlers.ContainsKey(typeof(TPacket)))
		{
			Handlers.Remove(typeof(TPacket));
		}
		Handlers.Add(typeof(TPacket), handler);
	}
}
