import os
from urllib.parse import urlparse, ParseResult
from netpyx import HttpClient
from requests import Response

from Packages.Pywidevine.cdm import cdm, deviceconfig


class Widevine(HttpClient):
    def __init__(self, url_server: str, pssh: str):
        super().__init__(silent=False)
        self._url_server = url_server
        self._pssh = pssh
        self._cdm = cdm.Cdm()
        self._device = deviceconfig.DeviceConfig(deviceconfig.device_android_generic_8162)
        self._session_id = None
        self._data_post = None
        self._parsed_url: ParseResult = urlparse(self._url_server)

    def __enter__(self):
        return self

    def start_session(self) -> None:
        self._session_id = self._cdm.open_session(self._pssh, self._device)
        self._data_post = self._cdm.get_license_request(self._session_id)

    def close_session(self) -> None:
        self._cdm.close_session(self._session_id)
        self._session_id = None
        self._data_post = None

    def get_response_server(self) -> Response:
        try:
            return self.post(self._url_server, self._data_post)
        except Exception as e:
            print(f"Error during request: {e}")



    def get_keys(self, license_base64) -> list[str] | None:
        self._cdm.provide_license(self._session_id, license_base64)
        decrypt_keys = []
        for key in self._cdm.get_keys(self._session_id):
            if key.type == "CONTENT":
                decrypt_keys.append("{}:{}".format(key.kid.hex(), key.key.hex()))
        if len(decrypt_keys) > 0:
            return decrypt_keys
        else:
            print("No Widevine keys found")
            return None