import logging
from io import BytesIO

from PIL import Image
from django.core.files import File

logger = logging.getLogger(__name__)


def logs_adder(content):
    """
    This function is responsible for printing some logs to terminal.
    it takes a content and prints it to the terminal
    """
    if 'CRITICAL' in content:
        logger.warning(content)
    else:
        logger.error(content)
    print(content)


def institute_sort_by_converter(sort_by):
    """
    This function converts the incoming sort_by parameter to an attribute of Institute table,
    so we can order the Institute records based on that attribute.
    """
    switcher = {
        'inst_name_asc': 'name',
        'inst_name_desc': '-name',
        'inst_created_asc': 'created_at',
        'inst_created_desc': '-created_at',
    }
    return switcher.get(sort_by, None)


def access_sort_by_converter(sort_by):
    """
    This function converts the incoming sort_by parameter to an attribute of Access table,
    so we can order the Access records based on that attribute.
    """
    switcher = {
        'inst_name_asc': 'institute_name',
        'inst_name_desc': '-institute_name',
        'inst_created_asc': 'institute_created_at',
        'inst_created_desc': '-institute_created_at',
        'email_asc': 'user__email',
        'email_desc': '-user__email',
    }
    return switcher.get(sort_by, None)


def institute_student_sort_by_converter(sort_by):
    """
    This function converts the incoming sort_by parameter to an attribute of InstituteStudent table,
    so we can order the InstituteStudent records based on that attribute.
    """
    switcher = {
        'first_name_asc': 'first_name',
        'first_name_desc': '-first_name',
        'last_name_asc': 'last_name',
        'last_name_desc': '-last_name',
        'email_asc': 'email',
        'email_desc': '-email',
        'referer_institute_student_identity_asc': 'referer_institute_student_identity',
        'referer_institute_student_identity_desc': '-referer_institute_student_identity',
        'id_asc': 'id',
        'id_desc': '-id',
    }
    return switcher.get(sort_by, None)


def public_resources_sort_by_converter(sort_by):
    """
    This function converts the incoming sort_by parameter to an attribute of PublicResource table,
    so we can order the PublicResource records based on that attribute.
    """
    switcher = {
        'title_asc': 'title',
        'title_desc': '-title',
        'created_at_asc': 'created_at',
        'created_at_desc': '-created_at',
    }
    return switcher.get(sort_by, None)


def sort_by_translator(sort_by):
    if sort_by.endswith("_asc"):
        return sort_by[0: -4]
    elif sort_by.endswith("_desc"):
        return "-" + sort_by[0: -5]
    elif sort_by == 'random':
        return '?'
    else:
        return sort_by


def compress_image(image, max_side_size):
    # resize image
    with Image.open(image) as opened_image:
        height_original = opened_image.height
        width_original = opened_image.width
        resized_image = None

        if height_original >= width_original and height_original > max_side_size:

            height = max_side_size
            width = int(height / height_original * width_original)
            resized_image = opened_image.resize((width, height))
        elif width_original >= height_original and width_original > max_side_size:

            width = max_side_size
            height = int(width / width_original * height_original)
            resized_image = opened_image.resize((width, height))

        if resized_image:
            opened_image_io = BytesIO()
            compressed_format = image.name.split('.')[-1].upper()
            if compressed_format == 'JPG':
                compressed_format = 'JPEG'
            resized_image.save(opened_image_io, format=compressed_format)
            compressed_image = File(opened_image_io, name=image.name)

            return compressed_image
        else:
            # we are duplicating the image because of AWS S3 save function problem
            # when we save a single instance of image in two database fields, two save functions will be run on the file.
            # The second one will fail with an error like this
            # File "/var/task/institute/views.py", line 134, in post
            #     institute.save()
            #   File "/var/task/django/db/models/base.py", line 743, in save
            #     self.save_base(using=using, force_insert=force_insert,
            #   File "/var/task/model_utils/tracker.py", line 243, in inner
            #     ret = original(instance, *args, **kwargs)
            #   File "/var/task/django/db/models/base.py", line 780, in save_base
            #     updated = self._save_table(
            #   File "/var/task/django/db/models/base.py", line 859, in _save_table
            #     values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
            #   File "/var/task/django/db/models/base.py", line 859, in <listcomp>
            #     values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
            #   File "/var/task/django/db/models/fields/files.py", line 302, in pre_save
            #     file.save(file.name, file.file, save=False)
            #   File "/var/task/django/db/models/fields/files.py", line 89, in save
            #     self.name = self.storage.save(name, content, max_length=self.field.max_length)
            #   File "/var/task/django/core/files/storage.py", line 54, in save
            #     name = self._save(name, content)
            #   File "/var/task/storages/backends/s3boto3.py", line 446, in _save
            #     content.seek(0, os.SEEK_SET)
            # ValueError: I/O operation on closed file.
            # Note that if the compression was done on a file, this problem would not arise
            # (compressed image is different from the original one therefore, one instance of a file will not be saved twice)
            with Image.open(image) as duplicate_image:
                duplicate_image_io = BytesIO()
                # image_format = image.name.split('.')[-1].upper()
                # if image_format == 'JPG':
                #     image_format = 'JPEG'
                # duplicate_image.save(duplicate_image_io, format=image_format)
                # duplicate_image= File(duplicate_image_io, name=image.name)
                # print("duplicated origin image")
                # return duplicate_image

                image_format = image.name.split('.')[-1].upper()
                if image_format == 'JPG':
                    image_format = 'JPEG'
                duplicate_image.save(duplicate_image_io, format=image_format)
                duplicate_image_file = File(
                    duplicate_image_io, name=image.name)
                return duplicate_image_file
