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

namespace skyscraper5.Dvb.DataBroadcasting
{
    class InteroperableObjectReference 
    {
        public InteroperableObjectReference(byte[] buffer)
            : this(new MemoryStream(buffer,false))
        {

        }
        public InteroperableObjectReference(MemoryStream ms)
        {

            uint typeIdLength = ms.ReadUInt32BE();
            if (ms.GetAvailableBytes() < typeIdLength)
                return;
            TypeId = Encoding.ASCII.GetString(ms.ReadBytes(typeIdLength));
            TypeId = TypeId.Trim((char)0);

            if (typeIdLength % 4 != 0)
            {
                for (int i = 0; i < (4 - (typeIdLength % 4)); i++)
                {
                    ms.ReadUInt8();
                }
            }

            uint taggedProfilesCount = ms.ReadUInt32BE();
            TaggedProfiles = new TaggedProfile[taggedProfilesCount];
            for (uint i = 0; i < taggedProfilesCount; i++)
            {
                TaggedProfiles[i] = new TaggedProfile();
                TaggedProfiles[i].ProfileIdTag = ms.ReadUInt32BE();
                uint profileDataLength = ms.ReadUInt32BE();
                TaggedProfiles[i].ProfileData = ms.ReadBytes(profileDataLength);
            }
        }

        public string TypeId { get; private set; }

        public TaggedProfile[] TaggedProfiles { get; private set; }
    }
}
