import json
from urllib.parse import quote

from actionstreamer.CommonFunctions import get_exception_info, send_signed_request
from actionstreamer.Config import WebServiceConfig
from actionstreamer.Result import StreamResult, StandardResult
from actionstreamer.Model import Stream, CreateStream

def create_stream(ws_config: WebServiceConfig, device_serial: str, create_stream: CreateStream) -> StreamResult:

    stream_result = StreamResult()

    try:
        device_serial = device_serial.replace(" ", "")
        device_serial = quote(device_serial)

        method = "POST"
        path: str = 'v1/stream/'
        url: str = ws_config.base_url + path
        headers = {"Content-Type": "application/json"}
        parameters: dict[str, str] = {}
        body = json.dumps(create_stream.to_dict())

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

        stream_result.code = result.code
        stream_result.description = result.description

        if result.code == 200:
            json_dict = json.loads(result.description)
            stream_result.stream = Stream(**json_dict)

            stream_result.code = result.code
            stream_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)
        stream_result.code = -1
        stream_result.description = "Exception in create_stream. Line number " + str(line_number)

    return stream_result


def delete_stream(ws_config: WebServiceConfig, stream_id: int) -> StandardResult:

    """
    Delete a stream record.
    
    Parameters:
    ws_config (Config.WebServiceConfig): The web service configuration.
    stream_id (int): The streamID.
    
    Returns:
    response_code: The API HTTP response code.
    response_string: The API HTTP response body
    """

    result = StandardResult()

    try:
        method = "DELETE"
        path = f'v1/stream/{stream_id}'
        url = ws_config.base_url + path
        headers = {"Content-Type": "application/json"}
        parameters: dict[str, str] = {}
        body = ''

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

    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)
        result.code = -1
        result.description = "Exception in delete_stream"

    return result
