using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.T2MI.Packets.Subparts;

namespace skyscraper5.T2MI.Packets
{
	[SkyscraperPlugin]
	[T2MiPacketType(0x33)]
    internal class _0x33_Subpart : T2MiPacket
    {
        public _0x33_Subpart(T2MIHeader header, byte[] buffer) : base(header, buffer)
        {
            if (buffer.Length < 15)
            {
                Valid = false;
                return;
            }
            MemoryStream ms = new MemoryStream(buffer, false);
            FefIndex = ms.ReadUInt8();
            TxIdentifier = ms.ReadUInt16BE();
            uint rfu1 = ms.ReadUInt32BE();
            SubpartIndex = ms.ReadUInt16BE();
            SubpartVariety = ms.ReadUInt16BE();
            uint readUInt32Be = ms.ReadUInt32BE();
            uint subpartLength = (readUInt32Be & 0x003fffff);
            if (subpartLength > ms.GetAvailableBytes())
            {
                Valid = false;
                return;
            }

            SubpartVariety = ms.ReadUInt16BE();
            subpartLength -= 2;
            switch (SubpartVariety)
            {
                case 0:
                    this.Subpart = new SubpartNull();
                    break;
                case 1:
                    this.Subpart = new SubpartIq(ms.ReadBytes(subpartLength));
                    break;
                case 2:
                    this.Subpart = new SubpartPrbs(ms.ReadBytes(subpartLength));
                    break;
                case 3:
                    this.Subpart = new SubpartTxSigFef();
                    break;
                default:
	                if (SubpartVariety > 0x0003)
	                {
		                PreferDiscard = true;
		                break;
	                }
                    throw new NotImplementedException(String.Format("T2-Mi Subpart {0:X4}", SubpartVariety));
            }

            Valid = true;
        }

        public bool PreferDiscard { get; private set; }
        public Subpart Subpart { get; private set; }

        public ushort SubpartVariety { get; private set; }

        public ushort SubpartIndex { get; private set; }

        public ushort TxIdentifier { get; private set; }

        public byte FefIndex { get; private set; }
    }
}
