using System.Net;
using log4net;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.Scraper;
using skyscraper5.Skyscraper.Scraper.Storage.InMemory;
using skyscraper8.Skyscraper.Scraper.Storage;

namespace skyscraper8.GSE;

public class Pts2Bbf
{
    private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
    
    public static void Run(FileInfo file, bool useUdpDecap = false, IPEndPoint ipEndPoint = null)
    {
        if (!file.Exists)
        {
            logger.Error("File not found: " + file.FullName);
            return;
        }

        IBbframeDeencapsulator dumper;
        if (useUdpDecap)
        {
            string changeExtension = Path.ChangeExtension(file.FullName, ".sdecap");
            BbfUdpDecap.UdpDecapFileOutput udpDecapSink = new BbfUdpDecap.UdpDecapFileOutput(new FileInfo(changeExtension));

            if (ipEndPoint == null)
            {
                ipEndPoint = new IPEndPoint(IPAddress.Parse("239.199.2.1"), 1234);
            }
            BbfUdpDecap bbfUdpDecap = new BbfUdpDecap();
            bbfUdpDecap.SetTargetPort(ipEndPoint.Port);
            bbfUdpDecap.SetTargetIp(ipEndPoint.Address);
            bbfUdpDecap.Sink = udpDecapSink;
            dumper = bbfUdpDecap;
        }
        else
        {
            string changeExtension = Path.ChangeExtension(file.FullName, ".sbbf");
            dumper = new BbframeDumper(new FileInfo(changeExtension));
        }
        
        FileStream fileStream = file.OpenRead();
        
        TsContext mpeg2 = new TsContext();
        mpeg2.RegisterPacketProcessor(0x010e, new Stid135BbFrameReader(null, dumper));
        DataStorage dataStorage = new InMemoryScraperStorage();
        ObjectStorage objectStorage = new NullObjectStorage();
        SkyscraperContext skyscraper = new SkyscraperContext(mpeg2, dataStorage, objectStorage);
        skyscraper.InitalizeFilterChain();
        skyscraper.IngestFromStream(fileStream);
        
        fileStream.Close();
        logger.Info("Pts2Bbf finished");
    }
}