using System;
using QCRPG.Framework;

namespace QCRPG.TSL.BT.Packets;

public class EdlPeek8Request : PacketBase
{
	public class UserFieldsWrapper
	{
		private const uint _SubOpcode = 2u;

		private uint _Address;

		private uint _DataLength;

		public uint SubOpcode => 2u;

		public uint Address
		{
			get
			{
				return _Address;
			}
			set
			{
				_Address = value;
			}
		}

		public uint DataLength
		{
			get
			{
				return _DataLength;
			}
			set
			{
				if (value > 255)
				{
					throw new Exception("Maximum possible value for DataLength is 0xFF");
				}
				_DataLength = value;
			}
		}
	}

	private const uint _Opcode = 64512u;

	private Type[] expectedResponseTypes = new Type[2]
	{
		typeof(EdlUploadResponse),
		typeof(CommandCompleteForNop)
	};

	private PacketInfoBase info;

	private uint _PayloadLength;

	public UserFieldsWrapper _UserFields = new UserFieldsWrapper();

	public override PacketType Type => PacketType.Command;

	public override Type[] ExpectedResponseTypes => expectedResponseTypes;

	public override PacketInfoBase Info
	{
		get
		{
			if (info == null)
			{
				info = new EdlPeek8RequestInfo(this);
			}
			return info;
		}
	}

	public uint Opcode => 64512u;

	public uint PayloadLength
	{
		get
		{
			ToBitString();
			return _PayloadLength;
		}
	}

	public UserFieldsWrapper UserFields => _UserFields;

	public override void SetDefaultValues()
	{
		UserFields.DataLength = 1u;
	}

	protected override bool FromBitBuilder(ref BitBuilder bitBuilder)
	{
		if (bitBuilder.RemoveBitsAsUintLittleEndian(16) != Opcode)
		{
			return false;
		}
		_PayloadLength = bitBuilder.RemoveBitsAsUint(8);
		int numberOfBits = bitBuilder.GetNumberOfBits();
		if (numberOfBits > _PayloadLength * 8 + 7)
		{
			return false;
		}
		if (numberOfBits < _PayloadLength * 8)
		{
			return false;
		}
		if (bitBuilder.RemoveBitsAsUint(8) != UserFields.SubOpcode)
		{
			return false;
		}
		UserFields.Address = bitBuilder.RemoveBitsAsUintLittleEndian(32);
		UserFields.DataLength = bitBuilder.RemoveBitsAsUint(8);
		if (bitBuilder.GetNumberOfBits() > 7)
		{
			return false;
		}
		return true;
	}

	public override string ToBitString()
	{
		BitBuilder bitBuilder = new BitBuilder();
		bitBuilder.AddBitsAsUintLittleEndian(Opcode, 16);
		int numberOfBits = bitBuilder.GetNumberOfBits();
		bitBuilder.AddBitsAsUint(0u, 8);
		bitBuilder.AddBitsAsUint(UserFields.SubOpcode, 8);
		bitBuilder.AddBitsAsUintLittleEndian(UserFields.Address, 32);
		bitBuilder.AddBitsAsUint(UserFields.DataLength, 8);
		_PayloadLength = (uint)((bitBuilder.GetNumberOfBits() - numberOfBits - 8) / 8);
		if ((bitBuilder.GetNumberOfBits() - numberOfBits - 8) % 8 != 0)
		{
			_PayloadLength++;
		}
		bitBuilder.ChangeBitsAsUint(numberOfBits, _PayloadLength, 8);
		return bitBuilder.ToString();
	}
}
