import requests
from requests.auth import HTTPBasicAuth

from django.conf import settings
from .models import GotifyUser


def create_user(username: str, password: str) -> dict:
    """Creates a user on the Gotify instance.

    :param username: The name of the user to be created.
    :param password: The password of the user to be created.
    """

    data = {
        'admin': False,
        'name': username,
        'pass': password
    }

    response = requests.post(
        url=f"http://{settings.GOTIFY_CONFIG['HOST']}/user",
        auth=HTTPBasicAuth(
            settings.GOTIFY_CONFIG['USERNAME'],
            settings.GOTIFY_CONFIG['PASSWORD'],
        ), 
        json=data
    )

    if response is not None:
        response.raise_for_status()

    return response.json()


def create_application(username: str, password: str) -> dict:
    """Creates an application on the Gotify instance.

    :param username: The user for whom an application will be created.
    :param password: The user's password.
    """

    data = {
        'defaultPriority': 6,
        'description': 'A remote patient health monitoring system.',
        'name': 'Medwings'
    }

    response = requests.post(
        url=f"http://{settings.GOTIFY_CONFIG['HOST']}/application",
        auth=HTTPBasicAuth(username, password), 
        json=data
    )

    if response is not None:
        response.raise_for_status()

    return response.json()


def upload_application_picture(username: str, password: str, app_id: int):
    with open('/app/static/medwings/images/logo/medwings-logo.png', 'rb') as image_file:
        response = requests.post(
            url=f"http://{settings.GOTIFY_CONFIG['HOST']}/application/{app_id}/image",
            auth=HTTPBasicAuth(
                username,
                password,
            ), 
            files={
                'file': image_file
            }
        )

    if response is not None:
        response.raise_for_status()
