#!/usr/bin/python3

import requests
from typing import Dict, Any
requests.packages.urllib3.disable_warnings()
from libs.config import CONFIG


def api_call(method: str, url: str, headers: Dict[str, Any] = None, payload = None) -> requests.models.Response:
    try:
        response = requests.request(method, url, headers=headers, data=payload, verify=False)
        response.raise_for_status()
    except requests.exceptions.HTTPError as HTTPError:
        print(f"HTTP Error: {HTTPError}")
    except requests.exceptions.ConnectionError:
        print(f"Can't connect to {url}")
    except requests.exceptions.Timeout:
        print(f"Timeout of request to {url}")
    except requests.exceptions.RequestException as ReqError:
        print(f"RequestException error has occured: {ReqError}")

    if method != "GET":
        print(response.text)
    if response.status_code >= 200 or response.status_code < 300:
        return response
    elif response.status_code == 401:
        print("Unauthorized access. Check your credentials in .env and the XiVO webservices configuration.")
        print("ws_user and ws_pass must be the same as user and password in the WEBI")
        print("ACL must be set to '#'")
        exit()
    else:
        print(f"Error: {response.status_code}")
        exit()


HEADERS = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": f"{CONFIG['auth']}"
}
