# -*- coding: utf-8 -*-
from filer.fields.image import AdminImageWidget, AdminImageFormField, FilerImageField
from filer.models import File


# https://stackoverflow.com/questions/27033485/how-to-crop-an-image-selected-with-django-filer-in-django-admin
class CroppableImageWidget(AdminImageWidget):
    def render(self, name, value, attrs=None):
        if value:
            file_obj = File.objects.get(pk=value)
            attrs = attrs or {}
            attrs.update({
                'class': 'crop-thumb',
                'data-thumbnail-url':
                    file_obj.thumbnails['admin_sidebar_preview'],
                'data-field-name': name,
                'data-org-width': file_obj.width,
                'data-org-height': file_obj.height,
            })

        return super().render(name, value, attrs)

    class Media:
        js = [
            'filer/js/addons/popup_handling.js',
            'cms/js/libs/jquery.min.js',
            'image_cropping/js/jquery.Jcrop.min.js',
            'image_cropping/image_cropping.js',
        ]
        css = {'all': ('image_cropping/css/jquery.Jcrop.min.css', 'image_cropping/css/admin_fix.css')}


class CroppableFormField(AdminImageFormField):
    widget = CroppableImageWidget


class CroppableFilerImageField(FilerImageField):
    default_form_class = CroppableFormField


# https://gist.github.com/specialunderwear/9d917ddacf3547b646ba
def AbstractClassWithoutFieldsNamed(cls, *excl):
    if cls._meta.abstract:
        remove_fields = [f for f in cls._meta.local_fields if f.name in excl]
        for f in remove_fields:
            cls._meta.local_fields.remove(f)
        return cls
    else:
        raise Exception("Not an abstract model")
