using System;
using System.Collections.Generic;
using QCRPG.Framework;
using QCRPG.TSL.BT.Packets;

namespace QCRPG.TSL.BT;

public class BTPacketHelper
{
	private BTPacketList btPacketList;

	private Dictionary<uint, List<Type>> opCodeToPacketTypeMap = new Dictionary<uint, List<Type>>();

	public BTPacketHelper(BTPacketList btPacketList)
	{
		this.btPacketList = btPacketList;
		BuildOpCodeToPacketTypeMap();
	}

	public List<Type> GetPacketTypesMatchingOpCode(uint opCode)
	{
		if (opCode > 65535)
		{
			throw new Exception("Invalid opCode: 0x" + opCode.ToString("X"));
		}
		try
		{
			return opCodeToPacketTypeMap[opCode];
		}
		catch (KeyNotFoundException)
		{
			if ((opCode & 0xE) == 14)
			{
				List<Type> list = new List<Type>();
				list.Add(typeof(GenericCommand));
				return list;
			}
			if ((opCode & 0xE) != 8192 && (opCode & 0xE) != 16384)
			{
				_ = opCode & 0xE;
				_ = 24576;
			}
			throw new Exception($"Op code 0x{opCode:X4} not found");
		}
	}

	private void BuildOpCodeToPacketTypeMap()
	{
		foreach (PacketBase packet in btPacketList.Packets)
		{
			if (packet.Type == PacketType.Command)
			{
				byte[] array = packet.ToByteArray();
				uint key = (uint)((array[1] << 8) | array[0]);
				if (!opCodeToPacketTypeMap.ContainsKey(key))
				{
					opCodeToPacketTypeMap.Add(key, new List<Type>());
				}
				opCodeToPacketTypeMap[key].Add(packet.GetType());
			}
		}
	}
}
