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

namespace skyscraper5.T2MI.Packets
{
	[SkyscraperPlugin]
	[T2MiPacketType(0x11)]
    public class _0x11_L1Future : T2MiPacket
    {
        public _0x11_L1Future(T2MIHeader header, byte[] buffer) : base(header, buffer)
        {
            if (buffer.Length == 0 || buffer.Length == 1)
            {
                Valid = false;
                return;
            }
            MemoryStream ms = new MemoryStream(buffer, false);
            FrameIndex = ms.ReadUInt8();
            ms.ReadUInt8();     //RFU
            FutureData = new FutureDataFields(ms);
            Valid = FutureData.Valid;
        }

        public byte FrameIndex { get; private set; }

        public FutureDataFields FutureData { get; private set; }

        public class FutureDataFields : Validatable
        {
            public FutureDataFields(MemoryStream ms)
            {
                if (2 > ms.GetAvailableBytes())
                {
                    Valid = false;
                    return;
                }
                ushort l1dynNextLen = ms.ReadUInt16BE();
                if (l1dynNextLen > ms.GetAvailableBytes())
                {
                    Valid = false;
                    return;
                }
                L1DynNext = ms.ReadBytes(8 * (l1dynNextLen / 8));

                ushort l1dynNext2Len = ms.ReadUInt16BE();
                if (l1dynNext2Len > ms.GetAvailableBytes())
                {
                    Valid = false;
                    return;
                }
                L1DynNext2 = ms.ReadBytes(8 * (l1dynNext2Len / 8));

                byte numInband = ms.ReadUInt8();
                for (int i = 0; i < numInband; i++)
                {
                    byte plpId = ms.ReadUInt8();
                    ushort inbandLen = ms.ReadUInt16BE();
                    if (inbandLen > ms.GetAvailableBytes())
                    {
                        Valid = false;
                        return;
                    }
                    if (InBands == null)
                        InBands = new byte[255][];
                    InBands[plpId] = ms.ReadBytes(8 * (inbandLen / 8));
                }
                Valid = true;
            }

            public byte[] L1DynNext2 { get; private set; }

            public byte[] L1DynNext { get; private set; }
            
            public byte[][] InBands { get; private set; }
        }
    }
}
