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;

namespace skyscraper5.T2MI.Packets
{
	[SkyscraperPlugin]
	[T2MiPacketType(0x31)]
    public class _0x31_IqData : T2MiPacket
    {
        public _0x31_IqData(T2MIHeader header, byte[] buffer) : base(header, buffer)
        {
            if (buffer.Length < 3)
            {
                Valid = false;
                return;
            }

            MemoryStream ms = new MemoryStream(buffer, false);
            FefIndex = ms.ReadUInt8();
            var readUInt16Be = ms.ReadUInt16BE();
            RFU = (readUInt16Be & 0xff80) >> 7;
            S1Field = (readUInt16Be & 0x0070) >> 4;
            S2Field = (readUInt16Be & 0x000f);

            long numSamples = ms.GetAvailableBytes();
            numSamples *= 8;
            numSamples /= 24;
            IQ = new Tuple<int, int>[numSamples];

            for (long sample = 0; sample < numSamples; sample++)
            {
                byte bq1 = ms.ReadUInt8();
                byte bq2 = ms.ReadUInt8();
                byte bq3 = ms.ReadUInt8();

                int i = bq1;
                i <<= 4;
                i += ((bq2 & 0xf0) >> 4);
                if ((i & 0x00000800) != 0)
                    i = -1 & i;

                int q = bq2 & 0x0f;
                q <<= 8;
                q += bq3;
                if ((q & 0x00000800) != 0)
                    q = -1 & i;

                IQ[sample] = new Tuple<int, int>(i, q);
            }

            Valid = numSamples >= 1;
        }

        public int S2Field { get; private set; }

        public int S1Field { get; private set; }

        public int RFU { get; private set; }

        public byte FefIndex { get; private set; }

        public Tuple<int, int>[] IQ { get; private set; }
    }
}
