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

namespace QCRPG.TSL.ZigBee;

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

	private const ushort TABI_CMDHEADER_LEN = 4;

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

	private readonly int ftmHeaderLength;

	private readonly Dictionary<ZigBeePacketDataType, ushort> logCodes = new Dictionary<ZigBeePacketDataType, ushort> { 
	{
		ZigBeePacketDataType.Event,
		6571
	} };

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

	public override ushort FtmCommandCode => 5;

	protected override int FtmHeaderLength => ftmHeaderLength;

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

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

	public override void Send(OutgoingPacketData packetData)
	{
		if (packetData.bytes.Length >= 4)
		{
			byte[] array = new byte[packetData.bytes.Length - 4];
			if (packetData.bytes.Length >= 4)
			{
				Array.Copy(packetData.bytes, 4, array, 0, packetData.bytes.Length - 4);
			}
			base.Send(new OutgoingPacketData(array));
		}
	}

	protected override byte[] CreateFtmHeader(OutgoingPacketData packetData)
	{
		return FtmHeaderCmdId.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;
		byte[] array = new byte[8 + num2];
		List<byte> list = new List<byte>();
		byte[] collection = new byte[4] { 16, 0, 0, 0 };
		if (num == logCodes[ZigBeePacketDataType.Event])
		{
			list.AddRange(collection);
			byte[] bytes = BitConverter.GetBytes(num2);
			list.AddRange(bytes);
		}
		list.CopyTo(array);
		currentPacketReceived.CopyTo(16, array, list.Count, num2);
		receiveDataNotifier.NotifyObservers(new IncomingPacketData(array));
	}
}
