using Serilog;

namespace OF_DL.Widevine;

public class CDMApi
{
    private string? SessionId { get; set; }

    public byte[]? GetChallenge(string initDataB64, string certDataB64, bool offline = false, bool raw = false)
    {
        SessionId = CDM.OpenSession(initDataB64, Constants.DEVICE_NAME, offline, raw);
        if (SessionId == null)
        {
            Log.Debug("CDM.OpenSession returned null, unable to proceed with challenge generation");
            return null;
        }

        CDM.SetServiceCertificate(SessionId, Convert.FromBase64String(certDataB64));
        return CDM.GetLicenseRequest(SessionId);
    }

    public void ProvideLicense(string licenseB64)
    {
        if (SessionId == null)
        {
            throw new Exception("No session ID set. Could not provide license");
        }

        CDM.ProvideLicense(SessionId, Convert.FromBase64String(licenseB64));
    }

    public List<ContentKey> GetKeys()
    {
        if (SessionId == null)
        {
            throw new Exception("No session ID set. Could not get keys");
        }

        return CDM.GetKeys(SessionId);
    }
}
