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

__author__ = 'SDE'

from django.db import models
from datetime import datetime
# from ckeditor.fields import RichTextField
# from BaseModels.pil_graphic_utils import *
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import post_save, pre_save
from django.utils.text import slugify
from django.contrib.postgres.fields import JSONField
# from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.contenttypes.fields import GenericRelation


# add_introspection_rules([], ["^tinymce\.models\.HTMLField"])

from django.core.exceptions import ValidationError
import os

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path & filename
    valid_extensions = ['.jpg', '.png', '.svg'] # populate with the extensions that you allow / want
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension.')


class Manager_Enabled(models.Manager):
    def get_queryset(self):
        return super(Manager_Enabled,
		     self).get_queryset().filter(enable=True)


def get_unique_url_for_new_instance(instance, sender):
    url = instance.url
    if not instance.pk:
        if not instance.url:
            name = sender.objects.model.__name__
        else:
            name = instance.url
        from BaseModels.inter import get_unique_url
        url = get_unique_url(sender, name)

    return url


class BaseModel(models.Model):

    name = models.TextField(verbose_name=_('Название'),
                            help_text=_('Название'), null=True, blank=True)
    name_plural = models.TextField(verbose_name=_('Название (множественное число)'),
                                   null=True, blank=True)
    order = models.IntegerField(verbose_name=_('Очередность отображения'), null=True, blank=True)
    createDT = models.DateTimeField(auto_now_add=True, verbose_name=_('Дата и время создания'))
    modifiedDT = models.DateTimeField(verbose_name=_('Дата и время последнего изменения'), null=True, blank=True)
    enable = models.BooleanField(verbose_name=_('Включено'), default=True, db_index=True)

    json_data = models.JSONField(verbose_name=_('Дополнительные данные'), default=dict, blank=True)

    def __str__(self):
        if self.name:
            return self.name
        else:
            return str(self.id)

    def pop_node_by_name(self, node_name):
        if not self.json_data or not node_name in self.json_data:
            return None

        res = self.json_data[node_name]
        del self.json_data[node_name]
        self.save(update_fields=['json_data'])

        return res


    def get_node_by_name(self, node_name):
        if not self.json_data or not node_name in self.json_data:
            return None

        return self.json_data[node_name]

    def add_node_to_json_data(self, node_data, save=False):
        if not self.json_data:
            self.json_data = {}
        if type(self.json_data) == dict:
            self.json_data.update(node_data)
        elif type(self.json_data) == list:
            self.json_data.append(node_data)

        if save:
            self.save(update_fields=['json_data'])

        return self.json_data

    def save(self, not_change_modifiedDT=False, *args, **kwargs):
        if not not_change_modifiedDT:
            self.modifiedDT = datetime.now()
        super().save(*args, **kwargs)

    class Meta:
        abstract = True

    objects = models.Manager()
    enabled_objs = Manager_Enabled()


def preSave_BaseModel(sender, instance, **kwargs):
    if instance and instance.user_profile:
        instance.modifiedDT = datetime.now()


pre_save.connect(preSave_BaseModel, sender=BaseModel, dispatch_uid='pre_save_connect')


class BaseModelViewPage(BaseModel):
    url = models.TextField(verbose_name=_('URL привязанной страницы'), unique=True,
                           help_text=_(
                               'можно изменить адрес страницы (!!! ВНИМАНИЕ !!! поисковые системы потеряют страницу и найдут лишь спустя неделю...месяц)'))
    title = models.TextField(verbose_name=_('Заголовок'), null=True, blank=True)
    description = RichTextUploadingField(verbose_name=_('Краткое описание'), null=True, blank=True,  # max_length=240,
                                help_text=_('краткое описание страницы (до 240 символов)'))
    text = RichTextUploadingField(verbose_name=_('Полное описание'), null=True, blank=True, )
    # help_text=_(u'краткое описание страницы (до 240 символов)'))
    picture = models.FileField(upload_to='uploads/', verbose_name=_('Картинка'), null=True, blank=True,
                                validators=[validate_file_extension])
    # icon = FileBrowseField("Image", max_length=200, directory="files/", extensions=[".jpg"], blank=True, null=True)
    visible = models.BooleanField(verbose_name=_('Отображать'), default=True)
    # background_image_left = models.ImageField(verbose_name=_('Левая подложка'), blank=True, null=True)
    # background_image_right = models.ImageField(verbose_name=_('Правая подложка'), blank=True, null=True)


    seo_title = models.CharField(max_length=250, verbose_name=_('Title (80 знаков)'), null=True, blank=True)
    seo_description = models.CharField(max_length=250, verbose_name=_('Description (150 знаков)'), null=True,
                                       blank=True)
    seo_keywords = models.CharField(max_length=250, verbose_name=_('Keywords (200 знаков)'), null=True, blank=True)
    seo_text = RichTextUploadingField(verbose_name=_(u'Текст SEO статьи'), null=True, blank=True)

    FAQ_title = models.CharField(max_length=250, verbose_name=_(u'FAQ Заголовок'), null=True, blank=True)
    FAQ_items = GenericRelation('GeneralApp.FAQitem', related_query_name='grel_%(class)s_for_faq_item')

    blocks = GenericRelation('GeneralApp.Block', related_query_name='grel_%(class)s_for_block_item')

    slides = GenericRelation('SlidesApp.Slide', related_query_name='grel_%(class)s_for_block_item')

    class Meta:
        abstract = True

    def get_title(self):
        if self.seo_title:
            return self.seo_title
        elif self.title:
            return self.title
        else:
            return self.name

    def get_description(self):
        if self.seo_description:
            return self.seo_description
        else:
            return self.description

    def get_feedback_block(self):
        blocks = self.get_blocks()
        for block in blocks:
            if block.block_type == 'feedback_form':
                return block
        return None

    def get_slides(self):
        slides = self.slides.filter(enable=True).order_by('order')
        return slides

    def get_FAQ_items(self):
        return self.FAQ_items.filter(enable=True).order_by('order')

    def get_blocks(self):
        return self.blocks.filter(enable=True).order_by('order')


    def get_description_exists(self):
        if self.description:
            return True
        return False

    def get_text_exists(self):
        if self.text:
            return True
        return False


# @receiver(pre_save, sender=User)
def preSaveBaseModelViewPage(sender, instance, **kwargs):
    if instance:
        if not instance.url:
            name = 'section'
        else:
            name = instance.url
        from BaseModels.inter import get_unique_url
        instance.url = get_unique_url(sender, name)

    if not sender.url:
        sender.url = slugify(sender.name)


pre_save.connect(preSaveBaseModelViewPage, sender=BaseModelViewPage, dispatch_uid='pre_save_connect')


