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

namespace QCRPG.TSL.BT;

public class BTReceivePacketHandler : ReceivePacketHandlerBase
{
	private List<PacketType> dataTypeList = new List<PacketType>();

	private List<PacketType> eventTypeList = new List<PacketType>();

	private List<PacketType> commandTypeList = new List<PacketType>();

	private List<PacketType> enhancedLogTypeList = new List<PacketType>();

	private List<PacketBase> enhancedLogList = new List<PacketBase>();

	public BTReceivePacketHandler(PacketListBase packetList)
		: base(packetList)
	{
		dataTypeList.Add(PacketType.Data);
		eventTypeList.Add(PacketType.Notification);
		eventTypeList.Add(PacketType.Response);
		enhancedLogTypeList.Add(PacketType.EnhancedLog);
		commandTypeList.Add(PacketType.Command);
		foreach (PacketBase packet in packetList.Packets)
		{
			if (packet.Type == PacketType.EnhancedLog)
			{
				enhancedLogList.Add(packet);
			}
		}
	}

	protected override PacketBase ConvertBytesToPacket(PacketData packetData)
	{
		if (packetData is BTIncomingPacketData)
		{
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.IsoDataPacket)
			{
				IsoData isoData = new IsoData();
				if (isoData.FromByteArray(packetData.bytes))
				{
					return isoData;
				}
				throw new Exception("Invalid ISO packet: " + ((BTOutgoingPacketData)packetData).btPacketType);
			}
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.AclDataPacket)
			{
				return packetList.BytesToPacketOfType(packetData.bytes, dataTypeList);
			}
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.SynchronousDataPacket)
			{
				return packetList.BytesToPacketOfType(packetData.bytes, dataTypeList);
			}
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.Event)
			{
				return packetList.BytesToPacketOfType(packetData.bytes, eventTypeList);
			}
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.Command)
			{
				return packetList.BytesToPacketOfType(packetData.bytes, commandTypeList);
			}
			if (((BTIncomingPacketData)packetData).btPacketType == BTPacketDataType.EnhancedLog)
			{
				AclData aclData = new AclData();
				if (aclData.FromByteArray(packetData.bytes))
				{
					foreach (PacketBase enhancedLog in enhancedLogList)
					{
						try
						{
							if (enhancedLog.FromByteArray(aclData.UserFields.DataList.Select((uint x) => Convert.ToByte(x)).ToArray()))
							{
								return enhancedLog.DeepCopy();
							}
						}
						catch (Exception)
						{
						}
					}
				}
				throw new Exception("Unsupported BT enhanced log format: " + ((BTOutgoingPacketData)packetData).btPacketType);
			}
			throw new Exception("Unsupported BT packet type: " + ((BTOutgoingPacketData)packetData).btPacketType);
		}
		return packetList.BytesToPacket(packetData.bytes);
	}
}
