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

__author__ = 'SDE'

from django.contrib.admin.widgets import AdminFileWidget, AdminTextareaWidget
from django.forms import widgets
from django.utils.safestring import mark_safe
from django.db import models
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline, GenericStackedInline
from django.utils.translation import gettext as _

import re
# from modeltranslation.admin import TranslationAdmin

# from filebrowser.admin import


def get_base_fieldsets():

    fieldsets = [
        [None, {
            'classes': ['wide'],
            'fields': (
                ('name',),
                ('name_plural',),
                ('url'),
                'FAQ_title'
            )
        }],

        [None, {
            'classes': ['wide'],
            'fields': (
                ('enable', 'order'),
                ('open_left_curtain_when_render', 'open_right_curtain_when_render')
            )
        }],

        (_('Описание и текст'), {
            'classes': ['wide', 'collapse'],
            'fields': (
                'description', 'text',
            )
        }),

        (_('Промо ФОН'), {
            'classes': ['wide', 'collapse'],
            'fields': (
                'background_promo_show', 'background_promo_inherits',
                'background_image',
                'background_title', 'background_txt', 'background_dates_txt',
                'background_subred_txt', 'background_promo_url', 'background_txt_color'
            )
        }),

        (u'SEO', {
            'classes': ['wide', 'collapse'],
            'fields': (
                'seo_title',
                'seo_description',
                'seo_keywords',
                'seo_text'
            )
        }),

        (_('Партнерские ссылки'), {
            'classes': ['wide', 'collapse'],
            'fields': (
                'link_left_promo_show',
                'link_left_promo_logo',
                'link_left_promo_url',
                'link_left_promo_name',
                'link_left_promo_text',

                'link_right_promo_show',
                'link_right_promo_logo',
                'link_right_promo_url',
                'link_right_promo_name',
                'link_right_promo_text',
            )
        }),
    ]

    return fieldsets


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))


def init_formfield_for_dbfield(class_model, self, db_field, request, **kwargs):
    formfield = super(class_model, self).formfield_for_dbfield(db_field, request, **kwargs)
    if db_field.name == 'url' or db_field.name == 'name' or db_field.name == 'title' or db_field.name == 'name_plural':
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})
    if db_field.name == 'workListForServicePage':
        formfield.widget = admin.widgets.AdminTextInputWidget( attrs={'style': 'width: 80%'})
    if db_field.name == 'seo_title':
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})
    if db_field.name == 'seo_description' or db_field.name == 'seo_keywords':
        formfield.widget = admin.widgets.AdminTextareaWidget()
    if db_field.name in ('background_title', 'background_dates_txt', 'background_subred_txt', 'background_promo_url'):
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})
    if db_field.name in ['fixed_address']:
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})
    if db_field.name in ('background_txt', 'description'):
        formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 80%'})
    if db_field.name in ('lexems',):
        formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 80%'})
    # if db_field.name == 'answer':
    #     formfield.widget = admin.widgets.AdminTextareaWidget(attrs={'style': 'width: 80%'})
    if db_field.name in ['question', 'FAQ_title']:
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 80%'})

    # if db_field.name in ['text']:
    #     formfield.widget.attrs.update({'style': 'width: 80%'})

    if formfield and formfield.widget:
        # if type(formfield.widget) in (admin.widgets.AdminSplitDateTime, ):
        #     formfield.widget.attrs.update({'style': 'width: 400px'})

        if type(formfield.widget) in (admin.widgets.AdminTextareaWidget, ):
            formfield.widget.attrs.update({'style': 'width: 80%'})
        pass

    if db_field.name in ['url']:
        formfield.widget = admin.widgets.AdminTextInputWidget(attrs={'style': 'width: 500px'})


    return formfield


def get_image_thumb(self, obj):
    image_url = None

    try:
        if obj.image:
            image_url = obj.image.url
    except:
        image_url = None

    if not image_url:
        try:
            if obj.images_gallery:
                image_url = obj.images_gallery.first().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
            if not '.' in image_url:
                image_url = None
        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 style="max-height: 100px; max-width: 100px;" src="' + image_url + '" />') #width="60"
        return mark_safe(s)
    else:
        return '(none)'


class Admin_GenericBaseIconStackedInline(GenericStackedInline):

    def formfield_for_dbfield (self, db_field, **kwargs):
        return init_formfield_for_dbfield(Admin_GenericBaseIconStackedInline, self, db_field, **kwargs)

    def image_thumb(self, obj):
        return get_image_thumb(self, obj)

    image_thumb.short_description = _('Миниатюра')
    image_thumb.allow_tags = True



class Admin_BaseIconStackedInline(admin.StackedInline):

    def formfield_for_dbfield (self, db_field, **kwargs):
        return init_formfield_for_dbfield(Admin_BaseIconStackedInline, self, db_field, **kwargs)

    def image_thumb(self, obj):
        return get_image_thumb(self, obj)

    image_thumb.short_description = _('Миниатюра')
    image_thumb.allow_tags = True


class Admin_BaseIconTabularModel(admin.TabularInline):

    def formfield_for_dbfield (self, db_field, **kwargs):
         return init_formfield_for_dbfield(Admin_BaseIconTabularModel, self, db_field, **kwargs)

    def image_thumb(self, obj):
        return get_image_thumb(self, obj)

    image_thumb.short_description = _('Миниатюра')
    image_thumb.allow_tags = True


class Admin_BaseIconModel(admin.ModelAdmin):

    def description_exists(self, obj):

        if obj.description:
            s = obj.description[:30]
        else:
            s = '-'

        return s

    description_exists.short_description = _('Описание')
    description_exists.allow_tags = True

    def formfield_for_dbfield (self, db_field, request, **kwargs):
        return init_formfield_for_dbfield(Admin_BaseIconModel, self, db_field, request, **kwargs)

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

    def image_thumb(self, obj):
        return get_image_thumb(self, obj)

    image_thumb.short_description = _('Миниатюра')
    image_thumb.allow_tags = True


# from modeltranslation.admin import TranslationAdmin
# # class CustomTranslationAdmin(TranslationAdmin):
# #     # def formfield_for_dbfield(self, db_field, **kwargs):
# #     #     field = super().formfield_for_dbfield(db_field, **kwargs)
# #     #     self.patch_translation_field(db_field, field, **kwargs)
# #     #     return field
#
#
# class AdminTranslation_BaseIconModel(Admin_BaseIconModel, TranslationAdmin):
#
#     # def formfield_for_dbfield(self, db_field, **kwargs):
#     #     field = super(AdminTranslation_BaseIconModel, self).formfield_for_dbfield(db_field, **kwargs)
#     #     self.patch_translation_field(db_field, field, **kwargs)
#     #     return field
#
#     class Media:
#
#         js = (
#             'modeltranslation/js/force_jquery.js',
#             'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
#             'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js',
#             'modeltranslation/js/tabbed_translation_fields.js',
#         )
#         css = {
#             'screen': ('modeltranslation/css/tabbed_translation_fields.css',),
#         }