using DVBServices;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.Skyscraper.Scraper;
using skyscraper5.Skyscraper.Scraper.StreamAutodetection;
using skyscraper8.Skyscraper.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper8.EPGCollectorPort.SkyscraperSide.MediaHighway2
{
	//Look for PIDs 0x231, 0x234, and 0x236
	[SkyscraperPlugin]
	[Experimental]
	class Mhw2Contestant : Contestant, Mhw2EventHandler
	{
		
		public Mhw2Contestant(int pid) : base("MediaHighway 2", pid)
		{
			PacketProcessor = new PsiDecoder(pid, new Mhw2Parser(this));
			if (_logger == null)
			{
				_logger = PluginLogManager.GetLogger(GetType());
			}
		}

		public override void Dispose()
		{

		}

		public override void DeclareWinner(SkyscraperContext skyscraperContext, int pid, ProgramContext programContext)
		{
			Mhw2Scraper mhw2Scraper = skyscraperContext.PluginContext.FirstOrDefault(x => x is Mhw2Scraper) as Mhw2Scraper;
			if (mhw2Scraper == null)
			{
				mhw2Scraper = new Mhw2Scraper(skyscraperContext);
				skyscraperContext.PluginContext.Add(mhw2Scraper);
			}

			skyscraperContext.DvbContext.RegisterPacketProcessor(pid, new PsiDecoder(pid, new Mhw2Parser(mhw2Scraper)));
		}

		public override void Introduce(ProgramContext programContext)
		{

		}

		private byte[] deadSections;
		private static PluginLogger _logger;

		public void OnNonMhw2Traffic(int sourcePid, int sectionTableId, byte mhwType)
		{
			if (deadSections == null)
				deadSections = new byte[byte.MaxValue];
			deadSections[sectionTableId]++;

			if (deadSections[sectionTableId] == 1)
				Score--;
		}

		public void OnMhw2Channels(int sourcePid, MediaHighway2ChannelSection channelSection)
		{
			if (channelSection == null)
				return;

			if (channelSection.Channels.Count > 0)
			{
				_logger.Log(PluginLogLevel.Info, "Found MHW2 Channel Section in PID {0}", sourcePid);
				Score += channelSection.Channels.Count;
			}
		}

		public void OnMhw2Categories(int sourcePid, MediaHighway2CategorySection categorySection)
		{
			_logger.Log(PluginLogLevel.Info, "Found MHW2 Category Section in PID {0}", sourcePid);
			Score += categorySection.Categories.Count;
		}

		public void OnMhw2Titles(int sourcePid, MediaHighway2TitleSection titleSection)
		{
			_logger.Log(PluginLogLevel.Info, "Found MHW2 Title Section in PID {0}", sourcePid);
			Score++;
		}

		public void OnMhw2Summary(int sourcePid, MediaHighway2SummarySection summarySection)
		{
			_logger.Log(PluginLogLevel.Info, "Found MHW2 Summary Section in PID {0}", sourcePid);
			Score++;
		}
	}
}
