using skyscraper5.Skyscraper;

namespace skyscraper8.GSE;

public class BBHeader : Validatable
{
    public BBHeader(byte[] bbframe, int offset)
    {
        ReadOnlySpan<byte> BbHeaderSpan = new ReadOnlySpan<byte>(bbframe, offset, 10);
        
        //byte 1, MATYPE-1
        TsGs = (BbHeaderSpan[0] & 0xc0) >> 6;
        SisMis = (BbHeaderSpan[0] & 0x20) != 0; //1 single, 0 multi
        CcmAcm = (BbHeaderSpan[0] & 0x10) != 0; //1 ccm, 0 acm
        Issyi = (BbHeaderSpan[0] & 0x08) != 0;  //
        Npd = (BbHeaderSpan[0] & 0x04) != 0;
        Ro = (BbHeaderSpan[0] & 0x03);

        Matype2 = (BbHeaderSpan[1]);
        
        UserPacketLength = BbHeaderSpan[2] << 8 | BbHeaderSpan[3];
        UserPacketLength /= 8;
        
        DataFieldLength = BbHeaderSpan[4] << 8 | BbHeaderSpan[5];
        DataFieldLength /= 8;
        
        SyncByte = BbHeaderSpan[6];
        
        SyncD = BbHeaderSpan[7] << 8  | BbHeaderSpan[8];
        SyncD /= 8;

        //ChecksumValid = DvbCrc8.Compute(BbHeaderSpan) == 0;
        //Valid = ChecksumValid;
        Valid = true;
    }
    
    public int SyncD { get; private set; }

    public byte SyncByte { get; private set; }

    public int DataFieldLength { get; private set; }

    public int UserPacketLength { get; private set; }

    /// <summary>
    /// If MIS, this is the Input Stream Identifier
    /// </summary>
    public byte Matype2 { get; private set; }

    /// <summary>
    /// Transmission Roll-off factor
    /// </summary>
    public int Ro { get; private set; }

    /// <summary>
    /// Null Packet Deletion
    /// </summary>
    public bool Npd { get; private set; }

    /// <summary>
    /// If true, the ISSY field is inserted after UP
    /// </summary>
    public bool Issyi { get; set; }

    /// <summary>
    /// True if CCM, False if ACM
    /// </summary>
    public bool CcmAcm { get; private set; }

    /// <summary>
    /// True if SIS, False if MIS
    /// </summary>
    public bool SisMis { get; private set; }

    /// <summary>
    /// 0 = GS, packetized
    /// 1 = GS, continuous
    /// 2 = GSE-HEM
    /// 3 = Transport
    /// </summary>
    public int TsGs { get; private set; }

    public override string ToString()
    {
        return String.Format("TsGs: {0}, SyncByte: {1}, UPL: {2}", TsGs, SyncByte,UserPacketLength);
    }
}