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.Iso14496_1
{
    class Iso14496_1DescriptorUnpacker
    {
        private static Iso14496_1DescriptorUnpacker _instance;

        private Iso14496_1DescriptorUnpacker()
        {

        }

        public static Iso14496_1DescriptorUnpacker GetInstance()
        {
            if (_instance == null)
            {
                _instance = new Iso14496_1DescriptorUnpacker();
            }

            return _instance;
        }

        public IEnumerable<Iso14496_1Descriptor> UnpackDescriptors(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer, false);
            while (ms.GetAvailableBytes() > 0)
            {
                byte tag = ms.ReadUInt8();
                if (tag >= 0x15 && tag <= 0x3f)
                {
                    //I have ISO 14496-1 Second edition available.
                    //This area is reserved, and since there is no length in the descriptors,
                    //we can't know when the next descriptor starts, we'll just abort.
                    yield break;
                }

                if (tag >= 0x4b)
                {
                    //Above 0x4b is either reserved for OCI extensions, otherwise reserved,
                    //user private or forbidden according to ISO 14496-1 Second edition.
                    //This area is reserved, and since there is no length in the descriptors,
                    //we can't know when the next descriptor starts, we'll just abort.
                    yield break;
                }

                throw new NotImplementedException(this.GetType().Name);
            }
        }
    }
}
