using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Scraper.StreamAutodetection.Contestants;
using skyscraper8.Ses;
using skyscraper8.Tests.ClassDependencies.AsraBarkerTransponderTests;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper8.Tests
{
	public class AstraBarkerTransponderTests
	{
		private const string BARKER_TRANSPONDER_FILE_PATH = "C:\\Temp\\Astra1_12604_v_SGT-000000.ts";
		private Stream GetBarkerTransponder()
		{
			FileInfo fi = new FileInfo(BARKER_TRANSPONDER_FILE_PATH);
			if (!fi.Exists)
			{
				Debug.WriteLine(String.Format("Could not find file: {0}", BARKER_TRANSPONDER_FILE_PATH));
				return null;
			}
			return fi.OpenRead();
		}

		[Fact]
		public void TestAstraSdt()
		{
			Stream stream = GetBarkerTransponder();
			if (stream == null)
				return;

			SdtContestant contestant = new SdtContestant(0x002d);

			TsDescriptorUnpacker descriptorUnpacker = TsDescriptorUnpacker.GetInstance();
			for (byte i = 0x80; i < 0xfe; i++)
			{
				descriptorUnpacker.SetUserDefined(i, true);
			}
			descriptorUnpacker.SetUserDefined(0xfe, true);

			TsContext tsContext = new TsContext();
			tsContext.FilterChain = new List<skyscraper5.src.Mpeg2.PacketFilter.IPacketFilter>();
			tsContext.FilterChain.Add(new DummyFilter());
			tsContext.RegisterPacketProcessor(0x002d, contestant.PacketProcessor);

			byte[] buffer = new byte[188];
			while (stream.GetAvailableBytes() >= 188)
			{
				stream.Read(buffer, 0, 188);
				tsContext.PushPacket(buffer);
				if (contestant.Score >= 10)
					break;
			}
			stream.Close();
		}

		[Fact]
		public void TestAstraLcn()
		{
			Stream stream = GetBarkerTransponder();
			if (stream == null)
				return;

			SgtCandidate contestant = new SgtCandidate(0x0777);
			SgtCandidate contestant2 = new SgtCandidate(0x0776);

			TsDescriptorUnpacker descriptorUnpacker = TsDescriptorUnpacker.GetInstance();
			for (byte i = 0x80; i < 0xfe; i++)
			{
				descriptorUnpacker.SetUserDefined(i, true);
			}
			descriptorUnpacker.SetUserDefined(0xfe, true);

			TsContext tsContext = new TsContext();
			tsContext.FilterChain = new List<skyscraper5.src.Mpeg2.PacketFilter.IPacketFilter>();
			tsContext.FilterChain.Add(new DummyFilter());
			tsContext.RegisterPacketProcessor(0x0777, contestant.PacketProcessor);
			tsContext.RegisterPacketProcessor(0x0776, contestant2.PacketProcessor);

			byte[] buffer = new byte[188];
			while (stream.GetAvailableBytes() >= 188)
			{
				stream.Read(buffer, 0, 188);
				tsContext.PushPacket(buffer);
				bool winnerA = contestant.Score >= 10;
				bool winnerB = contestant2.Score >= 10;
				if (winnerA)
				{
					if (winnerB)
					{
						return;
					}
				}
			}
			stream.Close();
		}
	}
}
