using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Mpeg2.Psi.Model;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.Skyscraper.Scraper.Utils;
using skyscraper5.src.Teletext;
using skyscraper5.Teletext;
using skyscraper5.Teletext.Vps;
using skyscraper5.Teletext.Wss;

namespace skyscraper5.Skyscraper.Scraper.StreamAutodetection.Contestants
{
	[SkyscraperPlugin]
	class TeletextContestant : Contestant, ITeletextPageHandler, IDisposable
    {
        public TeletextContestant(int pid) : base("Teletext", pid)
        {
            PacketProcessor = new PesDecoder(new TeletextPesProcessor(this, 0, 0, 0, pid));
        }

        public void OnVpsData(int networkId, int transportStreamId, ushort programNumber, VpsDataBlock vpsDataField, int elementaryPid)
        {
            Score++;
        }

        public void OnWssData(int networkId, int transportStreamId, ushort programNumber, WssDataBlock wssDataBlock, int elementaryPid)
        {
            Score++;
        }

        public void OnTeletextPage(int networkId, int transportStreamId, ushort programNumber, TeletextMagazine magazine)
        {
            Score++;
        }

        public override void Dispose()
        {
            
        }

        public override void DeclareWinner(SkyscraperContext skyscraperContext, int pid, ProgramContext programContext)
        {
			if (!skyscraperContext.CurrentNetworkId.HasValue)
			{
				//Since we need the network id 
				skyscraperContext.DvbContext.RegisterPacketProcessor(pid, new PacketDiscarder());
				return;
			}

			if (!skyscraperContext.CurrentTransportStreamId.HasValue)
			{
				//We need the TSID for teletext, but we don't have it - we'll just have to discard this.
				skyscraperContext.DvbContext.RegisterPacketProcessor(pid, new PacketDiscarder());
				return;
			}

			if (programContext.Program == null)
			{
				programContext.Program = new ProgramMapping(0x1fff, 0x1fff);
			}
			TeletextPesProcessor ttp = new TeletextPesProcessor(skyscraperContext, skyscraperContext.CurrentNetworkId.Value, skyscraperContext.CurrentTransportStreamId.Value, programContext.ProgramNumber, pid);
			ttp.PrivateDataSpecifier = programContext.PrivateDataSpecifier;
			skyscraperContext.DvbContext.RegisterPacketProcessor(pid, new PesDecoder(ttp));
		}

        public override void Introduce(ProgramContext programContext)
        {
	        
        }

        public void OnMonochromeData(int networkId, int transportStreamId, ushort programNumber, MonochromeDataField result)
		{
            Score++;
		}
	}
}
