import base64
import logging
import os
import shutil

import bugsnag
import requests

from app.util import util

log = logging.getLogger(__name__)


class FileUtil:
    TMP_PATH = "/tmp/credit_fair"

    @classmethod
    def convert_to_base64(cls, agreement_pdf_path):
        with open(agreement_pdf_path, "rb") as document:
            return base64.b64encode(document.read())

    @classmethod
    def get_temp_file(cls, file_name=None):
        if not file_name:
            file_name = util.get_char_uuid(10)

        return f'{FileUtil.get_temp_directory()}/{file_name}'

    @classmethod
    def get_temp_directory(cls):
        return FileUtil.TMP_PATH

    @classmethod
    def create_directory(cls, directory_path):
        try:
            os.mkdir(directory_path)
            log.debug('Directory created at:{}'.format(directory_path))
        except FileExistsError:
            bugsnag.notify(Exception('FileExistsError - file_util'))
            log.debug('Directory already exists at: {}'.format(directory_path))

    @classmethod
    def remove_file(cls, file_path):
        try:
            if os.path.isdir(file_path):
                shutil.rmtree(file_path)
                log.debug("Removed dir at: {}".format(file_path))
            else:
                os.remove(file_path)
                log.debug("Removed file at: {}".format(file_path))
        except OSError:
            bugsnag.notify(Exception('OSError - file_util'))
            log.warning(f"File not present at: {file_path}")


FileUtil.create_directory(FileUtil.TMP_PATH)
