using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Iso14496_1.Descriptors
{
    [Iso14496_1Descriptor(0x02)]
    public class InitialObjectDescriptor : Iso14496_1Descriptor
    {
        public InitialObjectDescriptor(byte[] buffer)
        : base(buffer.Length)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            ushort readUInt16Be = ms.ReadUInt16BE();
            ObjectDescriptorId = (readUInt16Be & 0xffc0) >> 6;
            UrlFlag = (readUInt16Be & 0x0020) != 0;
            IncludeInlineProfileLevelFlag = (readUInt16Be & 0x0010) != 0;

            if (UrlFlag)
            {
                byte urlLength = ms.ReadUInt8();
                UrlString = Encoding.ASCII.GetString(ms.ReadBytes(urlLength));
            }
            else
            {
                OdProfileLevelIndication = ms.ReadUInt8();
                SceneProfileLevelIndication = ms.ReadUInt8();
                AudioProfileLevelIndication = ms.ReadUInt8();
                VisualProfileLevelIndication = ms.ReadUInt8();
                GraphicsProfileLevelIndication = ms.ReadUInt8();
            }

            UnpackDescriptors(ms.ReadBytes(ms.GetAvailableBytes()));
        }

        private void UnpackDescriptors(byte[] buffer)
        {
            IEnumerable<Iso14496_1Descriptor> descriptors = Iso14496_1DescriptorUnpacker.GetInstance().UnpackDescriptors(buffer);
            foreach (Iso14496_1Descriptor descriptor in descriptors)
            {
                string name = descriptor.GetType().Name;
                switch (name)
                {
                    default:
                        throw new NotImplementedException(name);
                }
            }
        }

        public byte? GraphicsProfileLevelIndication { get; private set; }

        public byte? VisualProfileLevelIndication { get; private set; }

        public byte? AudioProfileLevelIndication { get; private set; }

        public byte? SceneProfileLevelIndication { get; private set; }

        public byte? OdProfileLevelIndication { get; private set; }

        public string UrlString { get; private set; }

        public bool IncludeInlineProfileLevelFlag { get; private set; }

        public bool UrlFlag { get; private set; }

        public int ObjectDescriptorId { get; private set; }
    }
}
