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

namespace QCRPG.TSL.NFC.Packets;

public class WriteI2cRegister : PacketBase
{
	public class UserFieldsWrapper
	{
		private uint _RegisterAddress;

		private uint _Length;

		private List<uint> _DataList = new List<uint>();

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

		public uint Length
		{
			get
			{
				return _Length;
			}
			set
			{
				if (value > 255)
				{
					throw new Exception("Maximum possible value for Length is 0xFF");
				}
				_Length = value;
				while (_DataList.Count < _Length)
				{
					_DataList.Add(0u);
				}
				while (_DataList.Count > _Length)
				{
					_DataList.RemoveAt(_DataList.Count - 1);
				}
			}
		}

		public List<uint> DataList => _DataList;
	}

	private Type[] expectedResponseTypes = new Type[0];

	private PacketInfoBase info;

	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 WriteI2cRegisterInfo(this);
			}
			return info;
		}
	}

	public UserFieldsWrapper UserFields => _UserFields;

	public override void SetDefaultValues()
	{
		UserFields.RegisterAddress = 0u;
		UserFields.Length = 0u;
	}

	protected override bool FromBitBuilder(ref BitBuilder bitBuilder)
	{
		UserFields.RegisterAddress = bitBuilder.RemoveBitsAsUint(8);
		UserFields.Length = (uint)(bitBuilder.GetNumberOfBits() / 8);
		for (int i = 0; i < UserFields.DataList.Count; i++)
		{
			UserFields.DataList[i] = bitBuilder.RemoveBitsAsUint(8);
		}
		if (bitBuilder.GetNumberOfBits() > 7)
		{
			return false;
		}
		return true;
	}

	public override string ToBitString()
	{
		BitBuilder bitBuilder = new BitBuilder();
		bitBuilder.AddBitsAsUint(UserFields.RegisterAddress, 8);
		for (int i = 0; i < UserFields.DataList.Count; i++)
		{
			if (UserFields.DataList[i] > 255)
			{
				throw new Exception("UserFields.DataList[i] is > 0xFF");
			}
			bitBuilder.AddBitsAsUint(UserFields.DataList[i], 8);
		}
		return bitBuilder.ToString();
	}
}
