import json

from actionstreamer.Model import Token
from actionstreamer.Result import TokenResult
from actionstreamer.Config import WebServiceConfig
from actionstreamer.CommonFunctions import send_signed_request, get_exception_info


def create_publish_token(ws_config: WebServiceConfig, media_path: str) -> TokenResult:

    token_result = TokenResult()

    try:
        method: str = "POST"
        path: str = "v1/token/mediarouter/publish"
        url: str = ws_config.base_url + path

        headers: dict[str, str] = {}
        headers["Content-Type"] = "application/json"

        parameters: dict[str, str] = {}

        request_body: dict[str, str] = {}
        request_body["streamPath"] = media_path

        body: str = json.dumps(request_body)

        result = send_signed_request(ws_config, method, url, path, headers, parameters, body)

        if result.code == 200:
            json_dict = json.loads(result.description)
            token_result.token = Token(**json_dict)
            
            token_result.code = result.code
            token_result.description = result.description

    except Exception as ex:
        filename, line_number = get_exception_info()

        if filename is not None and line_number is not None:
            print(f"Exception occurred at line {line_number} in {filename}")

        print(ex)

        token_result.code = -1
        token_result.description = "Exception in create_publish_token. Line number " + str(line_number)

    return token_result