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

namespace QCRPG.TSL.FMHCI.Packets;

public class GenericEvent : PacketBase
{
	public class UserFieldsWrapper
	{
		private uint _EventCode;

		private uint _PayloadLength;

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

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

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

		public List<uint> PayloadList => _PayloadList;
	}

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

	private PacketInfoBase info;

	public UserFieldsWrapper _UserFields = new UserFieldsWrapper();

	public override PacketType Type => PacketType.Notification;

	public override Type[] ExpectedResponseTypes => expectedResponseTypes;

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

	public UserFieldsWrapper UserFields => _UserFields;

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

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