using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.T2MI
{
    public class T2MIHeader
    {
        public T2MIHeader(byte[] buffer)
        {
            PacketType = buffer[0];
            PacketCount = buffer[1];
            SuperframeIndex = (buffer[2] & 0xf0) >> 4;

            RFU = (buffer[2] & 0x0f);
            RFU <<= 5;
            RFU = ((buffer[3] & 0xf8) >> 3);

            T2MIStreamId = (buffer[3] & 0x07);

            (buffer[4], buffer[5]) = (buffer[5], buffer[4]);
            PayloadLength = BitConverter.ToUInt16(buffer, 4);
        }

        public ushort PayloadLength { get; private set; }

        public int T2MIStreamId { get; set; }

        public int RFU { get; private set; }

        public int SuperframeIndex { get; private set; }

        public byte PacketCount { get; set; }

        public byte PacketType { get; private set; }

        public int PayloadLengthBytes
        {
            get
            {
                if (PayloadLength % 8 == 0)
                    return (PayloadLength / 8) + 4;     //+4 damit wir die Checksum einfach mitnehmen können, höhöhö...
                else
                {
                    int result = PayloadLength / 8;
                    result++;
                    return result + 4;
                }
            }
        }

        public bool NeedPadding => PayloadLength % 8 != 0;
    }
}
