using log4net;
using skyscraper5.Dvb.DataBroadcasting;
using skyscraper8.GS;
using skyscraper8.Skyscraper.Scraper;

namespace skyscraper8.GSE;

class BbframeDeencapsulator3 : IBbframeDeencapsulator
{
    public BbframeDeencapsulator3(GsContextDto context)
    {
	    this.context = context;
    }

    private readonly GsContextDto context;
    private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
    private long numPushed;
    public void PushPacket(byte[] bbframe)
    {
        //byte 0, sync byte
        if (bbframe[0] != 0xb8)
        {
            if (numPushed == 0)
            {
                logger.InfoFormat("The stream started in the middle of a BBFrame, let's wait for the next one to start.");
            }
            return;
        }
        numPushed++;

        BBHeader bbHeader = new BBHeader(bbframe, 1);
        if (!bbHeader.Valid)
            return;


        if (mis == null)
            mis = new IMisHandler[256];
        if (mis[bbHeader.Matype2] == null)
        {
            mis[bbHeader.Matype2] = new MisHandlerProxy(context.MisClone(bbHeader.Matype2));
        }

		mis[bbHeader.Matype2].PushFrame(bbHeader, new ReadOnlySpan<byte>(bbframe, 11, bbframe.Length - 11));
		context.UiJunction?.OnBbframe(bbHeader, bbframe);
	}

    private IMisHandler[] mis;
}