using System.Collections.Generic;
using System.IO;
using skyscraper5.Dvb.Descriptors;
using skyscraper5.Dvb.Psi.Model;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Scorcher
{
	public class SdtGeneratorService
	{
		public SdtGeneratorService(ushort serviceId, bool eitScheduleFlag = false, bool eitPresentFollowingFlag = false, RunningStatus runningStatus = RunningStatus.Running, bool freeCaMode = false)
		{
			ServiceId = serviceId;
			EitScheduleFlag = eitScheduleFlag;
			EitPresentFollowingFlag = eitPresentFollowingFlag;
			descriptors = new List<TsDescriptor>();
			RunningStatus = runningStatus;
			FreeCaMode = false;
		}

		public ushort ServiceId { get; private set; }
		public bool EitScheduleFlag { get; }
		public bool EitPresentFollowingFlag { get; private set; }
		public RunningStatus RunningStatus { get; set; }
		public bool FreeCaMode { get; set; }

		private List<TsDescriptor> descriptors;

		public byte[] SerializeDescriptors()
		{
			MemoryStream ms = new MemoryStream();
			foreach (TsDescriptor descriptor in descriptors)
			{
				ms.WriteUInt8(descriptor.GetDescriptorId());    //descriptor_tag

				byte[] descriptorBytes = descriptor.Serialize();
				ms.WriteUInt8((byte)descriptorBytes.Length);    //descriptor_length
				ms.Write(descriptorBytes, 0, descriptorBytes.Length);
			}
			return ms.ToArray();
		}

		private bool hasName;

		public bool AddName(string name, string providerName, ServiceDescriptor.ServiceTypeCoding type)
		{
			if (hasName)
				return false;

			ServiceDescriptor sd = new ServiceDescriptor(name, providerName, type);
			descriptors.Add(sd);
			hasName = true;
			return true;
		}

		public void AddDescriptor(TsDescriptor descriptor)
		{
			descriptors.Add(descriptor);
		}
	}
}
