from typing import Union

import requests
from django.conf import settings

class MinioService:

    @staticmethod
    def check() -> bool:
        print("Checking MinIO availability")
        try:
            url= settings.AWS_HOST
            r = requests.put(url)
            if not (r.status_code >= 200 and r.status_code < 500):
                return False
        except:
            return False
        return True

    @staticmethod
    def create_file(filename: str, file: bytes) -> bool:
        """Create / save (or overwrite) an file on the minio storage.

        :param filename: filename
        :param file: bytes representation of the file
        :return: Whether file was successfully uploaded
        """
        try:
            url= settings.AWS_HOST + filename
            headers = {'Content-Type': 'binary/octet-stream'}
            r = requests.put(url,data=file,headers=headers)
            if r.status_code == 200:
                print("Successfully uploaded a file!")
            else:
                print("Something went wrong while creating")
        except:
            return False
        return True


    @staticmethod
    def read_file(filename: str) -> bytes:
        """Read  file on the minio storage.

        :param filename: filename
        :return: bytes representation of the file or None on error
        """
        file_bytes: Union[bytes, None] = None
        try:
            url = settings.AWS_HOST + filename
            response = requests.get(url, stream=True)
            file_bytes=response.content
        except:
            print("Error downloading file from minio")
        return file_bytes

    @staticmethod
    def delete_file(filename: str) -> bool:
        """Delete an file from the dropbox storage.

        :param filename: filename of the file
        :return: Whether file was successfully deleted
        """
        try:
            url = settings.AWS_HOST + filename
            r = requests.delete(url)
            if r.status_code == 204:
                print("Successfully deleted a file!")
            else:
                print("Something went wrong while deleting")
        except:
            return False
        return True