using moe.yo3explorer.skyscraper8.DVBI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace skyscraper8.DvbI
{
	internal class DvbIUtils
	{
		private DvbIUtils() { }

		private static XmlSerializer serviceListEntryPointSerializer;

		public static ServiceListEntryPoints UnpackServiceListEntryPoints(byte[] buffer)
		{
			if (serviceListEntryPointSerializer == null)
				serviceListEntryPointSerializer = new XmlSerializer(typeof(ServiceListEntryPoints));

			MemoryStream slepStream = new MemoryStream(buffer, false);
			object slepWrapped = serviceListEntryPointSerializer.Deserialize(slepStream);
			ServiceListEntryPoints serviceListEntryPoint = (ServiceListEntryPoints)slepWrapped;
			return serviceListEntryPoint;
		}

		private static XmlSerializer serviceListSerializer;
		public static ServiceListType UnpackServiceList(byte[] buffer)
		{
			if (serviceListSerializer == null)
				serviceListSerializer = new XmlSerializer(typeof(ServiceListType));

			MemoryStream slStream = new MemoryStream(buffer, false);
			object slWrapped = serviceListSerializer.Deserialize(slStream);
			ServiceListType slt = (ServiceListType)slWrapped;
			return slt;
		}

		public static IEnumerable<DvbiServiceList> FlattenServiceListEntryPoints(ServiceListEntryPoints input)
		{
			foreach(ServiceListEntryPointsProviderOffering offering in input.ProviderOffering)
			{
				foreach (ServiceListEntryPointsProviderOfferingServiceListOffering serviceListOffering in offering.ServiceListOffering)
				{
					DvbiServiceList serviceList = new DvbiServiceList();
					serviceList.Id = serviceListOffering.ServiceListId;
					serviceList.Name = serviceListOffering.ServiceListName;

					foreach(ServiceListEntryPointsProviderOfferingServiceListOfferingDelivery delivery in serviceListOffering.Delivery)
					{
						if (delivery.DASHDelivery != null && string.IsNullOrEmpty(serviceList.DashDelivery))
							serviceList.DashDelivery = delivery.DASHDelivery;
						if (delivery.DVBSDelivery != null && string.IsNullOrEmpty(serviceList.DvbSDelivery))
							serviceList.DvbSDelivery = delivery.DVBSDelivery[0].OrbitalPosition;
					}

					if (serviceListOffering.RelatedMaterial != null)
					{
						if (serviceListOffering.RelatedMaterial.MediaLocator != null)
						{
							serviceList.RelatedMaterial = serviceListOffering.RelatedMaterial.MediaLocator[0].Value;
						}
					}

					if (serviceListOffering.ServiceListURI != null)
					{
						serviceList.URI = serviceListOffering.ServiceListURI[0].URI;
					}

					yield return serviceList;
				}
			}
			yield break;
		}

		public static IEnumerable<DvbIService> FlattenServiceList(ServiceListType serviceList)
		{
			foreach (ServiceType service in serviceList.Items)
			{
				DvbIService child = new DvbIService();

				if (service.AdditionalServiceParameters != null)
					throw new NotImplementedException(nameof(service.AdditionalServiceParameters));

				if (service.ContentGuideServiceRef != null)
					throw new NotImplementedException(nameof(service.ContentGuideServiceRef));

				if (service.Item != null)
					child.RelatedItem = service.Item.ToString();

				if (service.NVOD != null)
					throw new NotImplementedException(nameof(service.NVOD));

				if (service.ParentalRating != null)
					throw new NotImplementedException(nameof(service.ParentalRating));

				if (service.ProminenceList != null)
				{
					child.Country = service.ProminenceList[0].country;
					child.Ranking = int.Parse(service.ProminenceList[0].ranking);
					child.Region = service.ProminenceList[0].region;
				}

				if (service.ProviderName != null)
					child.ProviderName = service.ProviderName[0].Value;

				if (service.RecordingInfo != null)
					throw new NotImplementedException(nameof(service.RecordingInfo));

				if (service.RelatedMaterial != null)
				{
					foreach(RelatedMaterialType rmt in service.RelatedMaterial)
					{
						if (rmt.HowRelated == null)
							continue;

						if (rmt.Items == null)
							continue;

						if (rmt.Items.Length == 0)
							continue;

						string key = rmt.HowRelated.href;
						string value = ExtractUrlFromRelatedMaterial(rmt);

						if (string.IsNullOrEmpty(value))
							continue;

						switch(key)
						{
							case "urn:dvb:metadata:cs:HowRelatedCS:2021:1001.2":
								child.LogoURL = value;
								break;
							default:
								throw new NotImplementedException(key);
						}
					}
				}

				if (service.ServiceDescription != null)
					child.ServiceDescription = service.ServiceDescription[0].Value;

				if (service.ServiceGenre != null)
				{
					GenreType genre = service.ServiceGenre[0];
					if (genre.Definition != null)
						throw new NotImplementedException(nameof(genre.Definition));

					if (genre.Name != null)
						throw new NotImplementedException(nameof(genre.Name));

					if (genre.metadataOriginIDRef != null)
						throw new NotImplementedException(nameof(genre.metadataOriginIDRef));

				}

				if (service.ServiceInstance != null)
				{
					foreach(object si in service.ServiceInstance[0].Items)
					{
						Type serviceInstanceType = si.GetType();
						if (serviceInstanceType == typeof(DVBSDeliveryParametersType))
						{
							DVBSDeliveryParametersType s = (DVBSDeliveryParametersType)si;
							if (s.DVBTriplet != null)
							{
								child.OriginalNetworkId = s.DVBTriplet.origNetId;
								child.ServiceId = s.DVBTriplet.serviceId;
								child.TransportStreamId = s.DVBTriplet.tsId;
							}
							child.FEC = s.FEC;
							child.Frequency = s.Frequency;
							child.Modcod = s.ModcodMode;
							child.ModulationSystem = s.ModulationSystem;
							child.ModulationType = s.ModulationType;
							child.OrbitalPosition = s.OrbitalPosition;
							child.Polarization = s.Polarization;
							child.RollOff = s.RollOff;
							child.SymbolRate = s.SymbolRate;
						}
						else if (serviceInstanceType == typeof(SATIPDeliveryParametersType))
						{
							SATIPDeliveryParametersType satip = (SATIPDeliveryParametersType)si;
							child.SatIpQueryParameters = satip.QueryParameters;
						}
					}
				}

				if (service.ServiceName != null)
					child.ServiceName = service.ServiceName[0].Value;

				if (service.ServiceType1 != null)
					child.ServiceType = service.ServiceType1.href;

				if (service.TargetRegion != null)
					throw new NotImplementedException();

				child.Id = service.UniqueIdentifier;
				child.Version = int.Parse(service.version);
				yield return child;
			}
			yield break;
		}

		private static string ExtractUrlFromRelatedMaterial(RelatedMaterialType rmt)
		{
			foreach(object o in rmt.Items)
			{
				if (o.GetType() == typeof(TVAMediaLocatorType))
				{
					TVAMediaLocatorType tVAMediaLocator = (TVAMediaLocatorType)o;
					foreach (object p in tVAMediaLocator.Items)
					{
						if (p.GetType() == typeof(ExtendedURIType))
						{
							ExtendedURIType extendedURI = (ExtendedURIType)p;
							return extendedURI.Value;
						}
					}
				}
				else
				{
					throw new NotImplementedException(o.GetType().FullName);
				}
			}
			return null;
		}
	}
}
