using skyscraper5.Dvb.Psi;
using skyscraper5.Mpeg2;
using skyscraper5.Mpeg2.Descriptors;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.Skyscraper.Scraper;
using skyscraper5.Skyscraper.Scraper.StreamAutodetection;
using skyscraper5.Skyscraper.Scraper.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper8.EPGCollectorPort.SkyscraperSide.Freesat
{
	[SkyscraperPlugin]
	internal class FreesatTdtContestant : Contestant
	{
		public FreesatTdtContestant(int pid) 
			: base("Freesat Timestamp", pid)
		{
			PacketProcessor = new PacketDiscarder();
		}

		public override void Dispose()
		{
		}

		public override void DeclareWinner(SkyscraperContext skyscraperContext, int pid, ProgramContext programContext)
		{
			FreesatTunnelScraper freesatScraper = skyscraperContext.PluginContext.FirstOrDefault(x => x is FreesatTunnelScraper) as FreesatTunnelScraper;
			if (freesatScraper == null)
			{
				freesatScraper = new FreesatTunnelScraper();
				freesatScraper.ConnectToStorage(skyscraperContext.DataStorage.GetPluginConnector(), skyscraperContext.OnPluginEvent);
				skyscraperContext.PluginContext.Add(freesatScraper);
			}

			skyscraperContext.DvbContext.RegisterPacketProcessor(pid, new PsiDecoder(pid, new TimetableParser(freesatScraper, freesatScraper)));
		}

		public override void Introduce(ProgramContext programContext)
		{
			if (programContext.PrivateDataSpecifier == 0x46534154)
			{
				UserDefinedDescriptor userDefinedDescriptor = programContext.GetFirstUserDefinedDescriptor();
				if (userDefinedDescriptor.DescriptorTag == 0xd1)
				{
					if (userDefinedDescriptor.Data[0] == 0x05)
					{
						if (userDefinedDescriptor.Data[1] == 0x06)
						{
							//Mine.
							Score += 10;
							return;
						}
					}
				}
			}
			Score = -100;
		}
	}
}
