# -*- coding: utf-8 -*-

__author__ = 'SDE'

from django.contrib.admin.widgets import AdminFileWidget, AdminTextareaWidget
from django.contrib.postgres.fields import JSONField
from django.utils.safestring import mark_safe
from django.db import models
from django.contrib import admin
from django.forms import widgets
import re
import json


# from modeltranslation.admin import TranslationAdmin

# from filebrowser.admin import


class AdminImageWidget(AdminFileWidget):

    def render(self, name, value, attrs=None, renderer=None):
        output = []
        if value and getattr(value, "url", None):
            output.append(
                u'<img src="{url}" style="max-width: 150px; max-height: 150px; width: auto; height: auto; margin: 10px 10px 10px 10px;"/> '.format(
                    url=value.url))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))

        return mark_safe(u''.join(output))


class Admin_BaseIconTabularModel(admin.TabularInline):

    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(Admin_BaseIconTabularModel, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'url' or db_field.name == 'name' or db_field.name == 'title' or db_field.name == 'comment':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 500px'})
        if db_field.name == 'workListForServicePage':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 800px'})
        if db_field.name == 'seo_title':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 800px'})
        if db_field.name == 'seo_description' or db_field.name == 'seo_keywords':
            formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 800px'})
        if db_field.name in ('text', 'description', 'seo_text'):
            formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 800px'})
        return formfield

    def image_thumb(self, obj):

        try:
            image_url = obj.picture.url
        except:
            image_url = None

        if not image_url:
            try:
                image_url = obj.icon.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.logo.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.photo.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.banner.photo.url
            except:
                image_url = None

        if image_url:
            s = str('<img src="' + image_url + '" width="60"/>')
            return mark_safe(s)
        else:
            return '(none)'

    image_thumb.short_description = u'Миниатюра'
    image_thumb.allow_tags = True


class PrettyJSONWidget(widgets.Textarea):

    def format_value(self, value):
        try:
            value = json.dumps(json.loads(value), indent=2, sort_keys=True, ensure_ascii=False)
            # these lines will try to adjust size of TextArea to fit to content
            row_lengths = [len(r) for r in value.split('\n')]
            self.attrs['rows'] = min(max(len(row_lengths) + 2, 10), 30)
            self.attrs['cols'] = min(max(max(row_lengths) + 2, 40), 120)
            return value
        except Exception as e:
            print("Error while formatting JSON: {}".format(e))
            # logger.warning("Error while formatting JSON: {}".format(e))
            return super(PrettyJSONWidget, self).format_value(value)


class Admin_BaseIconModel(admin.ModelAdmin):
    # from codemirror import CodeMirrorTextarea
    # codemirror_widget = CodeMirrorTextarea(
    #     mode="python",
    #     theme="cobalt",
    #     config={
    #         'fixedGutter': True
    #     },
    # )

    def formfield_for_dbfield(self, db_field, **kwargs):

        formfield = super(Admin_BaseIconModel, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'url' or db_field.name == 'name' or db_field.name == 'title':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 500px'})
        if db_field.name == 'workListForServicePage':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 800px'})
        if db_field.name == 'seo_title':
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 800px'})
        if db_field.name == 'seo_description' or db_field.name == 'seo_keywords':
            formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 800px'})
        if db_field.name in ('lexems',):
            formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 80%'})
        if db_field.name in ('type_full_name', 'properties_title_name', 'where_buy_title_name'):
            formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})

        return formfield

    formfield_overrides = {
        models.ImageField: {'widget': AdminImageWidget},
        JSONField: {'widget': PrettyJSONWidget}
    }

    def image_thumb(self, obj):

        try:
            image_url = obj.avatar.url
        except:
            image_url = None

        if not image_url:
            try:
                image_url = obj.picture.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.icon.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.main_photo().url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.offer.main_photo().url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.rel_product.main_photo().url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.logo.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.photo.url
            except:
                image_url = None

        if not image_url:
            try:
                image_url = obj.picture.url
            except:
                image_url = None

        if image_url:
            s = str('<img src="' + image_url + '" width="60"/>')
            return mark_safe(s)
        else:
            return '(none)'

    image_thumb.short_description = u'Миниатюра'
    image_thumb.allow_tags = True


from modeltranslation.admin import TranslationAdmin


class AdminTranslation_BaseIconModel(Admin_BaseIconModel, TranslationAdmin):
    class Media:
        js = (
            'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
            'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js',
            'modeltranslation/js/tabbed_translation_fields.js',
            # 'cked/ckeditor/ckeditor.js'
        )
        css = {
            'screen': ('modeltranslation/css/tabbed_translation_fields.css',),
        }
