using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DVBServices;
using skyscraper5.Mpeg2;

namespace skyscraper8.EPGCollectorPort.SkyscraperSide.MediaHighway2
{
	internal class Mhw2Parser : IPsiProcessor
	{
		private Mhw2EventHandler eventHandler;

		public Mhw2Parser(Mhw2EventHandler eventHandler)
		{
			this.eventHandler = eventHandler;
		}

		public void GatherPsi(PsiSection section, int sourcePid)
		{
			if (section.TableId == 0xc8)
			{
				byte[] bytes = section.GetData();
				switch (bytes[3])
				{
					case 0:
						try
						{
							MediaHighway2ChannelSection channelSection = MediaHighway2ChannelSection.ProcessMediaHighwayChannelTable(bytes);
							eventHandler.OnMhw2Channels(sourcePid, channelSection);
						}
						catch (NotImplementedException e)
						{
							Console.WriteLine(e);
							throw;
						}
						return;
					case 1:
						try
						{
							MediaHighway2CategorySection categorySection = MediaHighway2CategorySection.ProcessMediaHighwayCategoryTable(bytes);
							eventHandler.OnMhw2Categories(sourcePid, categorySection);
						}
						catch (NotImplementedException e)
						{
							Console.WriteLine(e);
							throw;
						}
						return;
					case 2:
						//Unknown
						break;
					case 3:
						//Unknown
						break;
					case 4:
						//Channel Name String Table, uninteresting.
						return;
					default:
						eventHandler.OnNonMhw2Traffic(sourcePid, section.TableId, bytes[3]);
						return;
				}
			}
			else if (section.TableId == 0xe6)
			{
				byte[] bytes = section.GetData();
				try
				{
					MediaHighway2TitleSection titleSection = MediaHighway2TitleSection.ProcessMediaHighwayTitleTable(bytes);
					if (titleSection != null)
					{
						eventHandler.OnMhw2Titles(sourcePid, titleSection);
					}
				}
				catch (Exception e)
				{
				}
				

				return;
			}
			else if (section.TableId == 0x96)
			{
				byte[] bytes = section.GetData();
				MediaHighway2SummarySection summarySection = MediaHighway2SummarySection.ProcessMediaHighwaySummaryTable(bytes);
				eventHandler.OnMhw2Summary(sourcePid,summarySection);
			}
			else
			{
				eventHandler.OnNonMhw2Traffic(sourcePid, section.TableId, section.GetData()[3]);
			}
		}
	}
}
