using System;
using System.Collections.Generic;
using System.Linq;
using QCRPG.Framework;

namespace QCRPG.TSL.BT;

public class ProtocolDiag : ProtocolDiagBase
{
	private const ushort FtmBTHciUserCmdId = 0;

	private readonly byte[] FtmHeaderCmdId = BitConverter.GetBytes((ushort)0);

	private readonly byte[] FtmHeaderCmdCrc = new byte[2];

	private byte[] ftmLogCrc = new byte[2];

	private readonly int ftmHeaderLength;

	private readonly Dictionary<BTPacketDataType, ushort> logCodes = new Dictionary<BTPacketDataType, ushort> { 
	{
		BTPacketDataType.Event,
		4966
	} };

	internal byte[] FtmLogCrc
	{
		set
		{
			ftmLogCrc = value;
		}
	}

	internal int FtmCrcLength
	{
		set
		{
			FTM_LOG_CRC_LENGTH = value;
		}
	}

	public override ushort FtmCommandCode => 4;

	protected override int FtmHeaderLength => ftmHeaderLength;

	public override ushort[] LogCodes => logCodes.Values.ToArray();

	public ProtocolDiag()
	{
		ftmHeaderLength = FtmHeaderCmdId.Length + 2 + FtmHeaderCmdCrc.Length;
	}

	protected override byte[] CreateFtmHeader(OutgoingPacketData packetData)
	{
		byte[] bytes = BitConverter.GetBytes((ushort)packetData.bytes.Length);
		return FtmHeaderCmdId.Concat(bytes).Concat(FtmHeaderCmdCrc).ToArray();
	}

	protected override int CalculatePayloadLength()
	{
		return (int)Conversions.ByteArrayToUint(currentPacketReceived.Skip(DiagHeader.Length + FtmHeaderCmdId.Length).ToArray(), 2, elementZeroIsMsb: false);
	}

	protected override void HandleCompleteAsyncLog()
	{
		ushort num = BitConverter.ToUInt16(currentPacketReceived.ToArray(), 6);
		int num2 = currentPacketReceived.Count - 16 - ftmLogCrc.Length;
		byte[] array = new byte[1 + num2];
		if (num == logCodes[BTPacketDataType.Event])
		{
			array[0] = 4;
		}
		currentPacketReceived.CopyTo(16, array, 1, num2);
		receiveDataNotifier.NotifyObservers(new IncomingPacketData(array));
	}
}
