using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.DsmCc.Message;
using skyscraper5.Dvb.DataBroadcasting.DataCarouselDescriptors;
using skyscraper5.Mhp.Descriptors;
using skyscraper5.Mpeg2;
using skyscraper5.Mpeg2.Descriptors;
using skyscraper5.Mpeg2.Psi.Model;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Dvb.DataBroadcasting.Biop
{
    class ModuleInfo
    {

        public ModuleInfo(DownloadInfoIndication.Module module, DownloadInfoIndication section3BDsmCcMessage, ProgramMapping programMapping, byte componentTag)
        {
            this.ModuleId = module.ID;
            this.ModuleVersion = module.Version;
            this.ModuleSize = module.Size;
            this.PmtComponentTag = componentTag;
            this.PmtMapping = programMapping;
            this.BlockSize = section3BDsmCcMessage.BlockSize;

            uint numBlocks = this.ModuleSize / section3BDsmCcMessage.BlockSize;
            if (this.ModuleSize % section3BDsmCcMessage.BlockSize != 0)
                numBlocks++;
            Blocks = new DownloadDataBlock[numBlocks];

            if (module.ModuleInfo.Length < 13)
                return;

            MemoryStream ms = new MemoryStream(module.ModuleInfo, false);

            ModuleTimeout = ms.ReadUInt32BE();
            BlockTimeout = ms.ReadUInt32BE();
            MinBlockTime = ms.ReadUInt32BE();

            byte tapsCount = ms.ReadUInt8();
            Taps = new Tap[tapsCount];
            for (int i = 0; i < tapsCount; i++)
            {
                if (ms.GetAvailableBytes() < 7)
                    return;
                Taps[i] = new Tap(ms);
            }

            if (ms.GetAvailableBytes() == 0)
                return;

            byte userInfoLength = ms.ReadUInt8();
            if (ms.GetAvailableBytes() < userInfoLength)
                return;
            byte[] userInfo = ms.ReadBytes(userInfoLength);
            if (userInfoLength > 2)
            {
                UnpackDescriptors(userInfo);
            }

            LooksLikeObjectCarousel = true;
        }

        public bool LooksLikeObjectCarousel { get; private set; }

        public ushort BlockSize { get; private set; }

        public ProgramMapping PmtMapping { get; private set; }

        public byte PmtComponentTag { get; private set; }

        public uint ModuleSize { get; private set; }

        public byte ModuleVersion { get; private set; }

        public ushort ModuleId { get; private set; }

        private void UnpackDescriptors(byte[] userInfo)
        {
            IEnumerable<TsDescriptor> descriptors = TsDescriptorUnpacker.GetInstance().UnpackDescriptors(userInfo, "DataCarousel");
            foreach (TsDescriptor tsDescriptor in descriptors)
            {
                string name = tsDescriptor.GetType().Name;
                switch (name)
                {
                    case nameof(CompressedModuleDescriptor):
                        this.CompressedModuleDescriptor = (CompressedModuleDescriptor)tsDescriptor;
                        break;
                    case nameof(CachingPriorityDescriptor):
                        this.CachingPriority = (CachingPriorityDescriptor)tsDescriptor;
                        break;
                    case nameof(Crc32Descriptor):
                        Crc32Descriptor crc32Descriptor = (Crc32Descriptor)tsDescriptor;
                        this.Crc32 = crc32Descriptor.CRC_32;
                        break;
                    case nameof(LabelDescriptor):
                        this.Label = ((LabelDescriptor)tsDescriptor).Label;
                        break;
                    case nameof(UserDefinedDescriptor):
                        //TODO: Check private data specifiers and friends
                        break;
                    default:
                        throw new NotImplementedException(name);
                }
            }
        }

        public uint? Crc32 { get; set; }

        public string Label { get; set; }

        public CachingPriorityDescriptor CachingPriority { get; set; }

        public CompressedModuleDescriptor CompressedModuleDescriptor { get; private set; }

        public Tap[] Taps { get; private set; }

        public uint MinBlockTime { get; private set; }

        public uint BlockTimeout { get; private set; }

        public uint ModuleTimeout { get; private set; }

        public DownloadDataBlock[] Blocks { get; }

        public bool BlocksComplete
        {
            get
            {
                for (int i = 0; i < Blocks.Length; i++)
                {
                    if (Blocks[i] == null)
                        return false;
                }

                return true;
            }
        }

        protected bool Equals(ModuleInfo other)
        {
            return ModuleVersion == other.ModuleVersion && ModuleId == other.ModuleId;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((ModuleInfo)obj);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(ModuleVersion, ModuleId);
        }

        public double DownloadProgress
        {
            get
            {
                double count = Blocks.Count(x => x != null);
                double result = count * 100.0 / Blocks.Length;
                return Math.Round(result, 1);
            }
        }

        public double TaggedProgress { get; set; }
    }
}
