from django.db import models
from BaseModels.base_models import *
from django.utils.translation import gettext_lazy as _
# from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
# from colorfield.fields import ColorField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
from colorfield.fields import ColorField

class StaticPage(BaseModelViewPage):
    promo_header = models.BooleanField(verbose_name='Промо-хэдер', default=False)

    class Meta:
        verbose_name = _('Статическая страница')
        verbose_name_plural = _('Статические страницы')

def preSave_StaticPage(sender, instance, **kwargs):
    instance.url = get_unique_url_for_new_instance(instance, sender)
pre_save.connect(preSave_StaticPage, sender=StaticPage, dispatch_uid='pre_save_connect')


block_type_choices = (
    ('photo_n_text', _('Фото с одной стороны + Текст с другой стороны')),
    ('main_block_w_subblocks', _('Блок с подблоками')),
    ('present_technology_block', _('описание и НАЗВАНИЕ слева + Картинка справа')),
    ('photo150_n_title', _('Фото 150x150 сверху + заголовок под фото')),
    ('how_work', _('Как с нами работать')),
    ('how_dev', _('Как ведется разработка')),
    ('feedback_form', _('Форма обратной связи')),
    ('projects_block', _('Блок проектов')),
    # ('slider', _('Галерея слайдов')),
)


class Block_Abstract(BaseModelViewPage):

    class Meta:
        verbose_name = _('Блок')
        verbose_name_plural = _('Блоки')
        abstract = True
        ordering = ['order']


class Block(Block_Abstract):

    content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    block_type = models.CharField(max_length=100, choices=block_type_choices, verbose_name=_('Тип блока'),
                                  default='photo_n_text')

    url = models.TextField(verbose_name=_('URL привязанной страницы'), null=True, blank=True)

    video_url = models.TextField(verbose_name=_('Ссылка на видео'), null=True, blank=True)

    bg_color = ColorField(verbose_name=_('Цвет фона'), default=None, null=True, blank=True)
    bg_image = models.FileField(
        upload_to='uploads/', verbose_name=_('Фоновое изображение блока'), null=True, blank=True,
        validators=[validate_file_extension]
    )
    bg_video_url = models.TextField(verbose_name=_('Ссылка на фоновое видео'), null=True, blank=True)

    but_title = models.CharField(max_length=100, verbose_name=_('Текст на кнопке'), null=True, blank=True)
    but_color = ColorField(verbose_name=_('Цвет кнопки'), default='#000000')

    but_icon = models.FileField(
        upload_to='uploads/', verbose_name=_('Пиктограмма для кнопки'), null=True, blank=True,
        validators=[validate_file_extension]
    )

    child_in_row_count = models.PositiveSmallIntegerField(
        verbose_name=_('Количество дочерних элементов в строке'), default=3)


    def get_widgets(self):
        return self.rel_widgets_for_block.filter(enable=True).order_by('order')

    class Meta:
        verbose_name = _('Блок на странице')
        verbose_name_plural = _('Блоки на странице')


# def preSave_Block(sender, instance, **kwargs):
#     instance.url = get_unique_url_for_new_instance(instance, sender)
# pre_save.connect(preSave_Block, sender=Block, dispatch_uid='pre_save_connect')




class WidgetForBlock(BaseModel):

    block = models.ForeignKey(
        Block, verbose_name=_('Родительский блок'), on_delete=models.CASCADE,
        related_name='rel_widgets_for_block'
    )

    title = models.TextField(verbose_name=_('Заголовок'), null=True, blank=True)
    description = RichTextUploadingField(verbose_name=_('Краткое описание'), null=True, blank=True)
    text = RichTextUploadingField(verbose_name=_('Дополнительное описание'), null=True, blank=True)

    picture = models.FileField(upload_to='uploads/', verbose_name=_('Картинка'), null=True, blank=True,
                                validators=[validate_file_extension])

    video_url = models.TextField(verbose_name=_('Ссылка на видео'), null=True, blank=True)

    # block_type = models.CharField(max_length=100, choices=block_type_choices, verbose_name=_('Тип блока'), default='photo_n_text')

    url = models.TextField(verbose_name=_('URL привязанной страницы'), null=True, blank=True)

    bg_color = ColorField(verbose_name=_('Цвет фона'), default=None, null=True, blank=True)

    but_title = models.CharField(max_length=100, verbose_name=_('Текст на кнопке'), null=True, blank=True)
    but_color = ColorField(verbose_name=_('Цвет кнопки'), default='#000000')

    but_icon = models.FileField(
        upload_to='uploads/', verbose_name=_('Пиктограмма для кнопки'), null=True, blank=True,
        validators=[validate_file_extension]
    )


    class Meta:
        verbose_name = _('Виджет в блоке')
        verbose_name_plural = _('Виджеты в блоке')



class Option(BaseModel):
    opt_type = models.CharField(max_length=250, verbose_name=_('Тип'), blank=True, null=True)
    prefix = models.CharField(max_length=250, verbose_name=_('Префикс'), blank=True, null=True)
    value = models.CharField(max_length=250, verbose_name=_('Значение'))
    picture = models.FileField(upload_to='uploads/', verbose_name=_('Миниатюра'), null=True, blank=True,
                                validators=[validate_file_extension])

    class Meta:
        verbose_name = _('Параметр')
        verbose_name_plural = _('Параметры')

class FAQitem(BaseModel):

    content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    question = models.TextField(verbose_name=_('Вопрос'))
    answer = RichTextUploadingField(verbose_name=_('Ответ'))

    def __str__(self):
        if self.question:
            return self.question
        else:
            return self.id

    class Meta:
        verbose_name = 'FAQ'
        verbose_name_plural = 'FAQs'



def work_time_default_from():
    dt = datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
    return dt

def work_time_default_to():
    dt = datetime.now().replace(hour=18, minute=0, second=0, microsecond=0)
    return dt

class Office(BaseModelViewPage):

    city = models.CharField(max_length=250, verbose_name=_(u'Город'))
    address = models.CharField(max_length=250, verbose_name=_(u'Адрес'), null=True, blank=True)
    workTime = models.CharField(
        max_length=220, verbose_name=_(u'Комментарий к времени работы'), null=True, blank=True
        # help_text='добавляется справа от времени работы'
    )
    work_time_from = models.TimeField(verbose_name=_('Время работы с'), default=work_time_default_from())
    work_time_to = models.TimeField(verbose_name=_('Время работы до'), default=work_time_default_to())
    # email = models.CharField(max_length=50,verbose_name=_(u'e-mail'), null=True, blank=True)

    # legal_name = models.CharField(max_length=250, verbose_name=_(u'Юридическое название'), null=True, blank=True)
    # legal_address = models.CharField(max_length=250, verbose_name=_(u'Адрес'), null=True, blank=True)
    # unp = models.CharField(max_length=250, verbose_name=_(u'Номер налогоплательщика'), null=True, blank=True)
    # urInfo = RichTextUploadingField(verbose_name=_(u'Юридическая информация'), null=True, blank=True)
    # legal_docs_text = models.TextField(
    #     verbose_name=_(u'Данные о свидетельствах и сертификатах'), null=True, blank=True
    # )
    #
    # fullContactInfo = RichTextUploadingField(
    #     verbose_name=_(u'Контактные данные'), null=True, blank=True)
    # map_code = models.TextField(verbose_name=_(u'код карты'), null=True, blank=True)
    #
    # main_office = models.BooleanField(verbose_name='Главный офис', default=False)
    #
    # gps_longitude = models.DecimalField(
    #     max_digits=22, decimal_places=16, verbose_name='GPS Долгота', blank=True, null=True
    #  )
    # gps_latitude = models.DecimalField(
    #     max_digits=22, decimal_places=16, verbose_name='GPS Широта', blank=True, null=True
    # )
    #
    # footer_info = RichTextUploadingField(verbose_name=_('Информация в подвале'), null=True, blank=True)

    def __str__(self):
        name_list = []
        if self.city:
            name_list.append(self.city)
        if self.address:
            name_list.append(self.address)
        if name_list:
            return ' '.join(name_list)

        return self.id

    def save(self, *args, **kwargs):
        # self.order = 0
        super(Office, self).save(*args, **kwargs)

    def contacts(self):
        return Contact.objects.filter(enable=True, office=self).order_by('order')

    def first_phone(self):
        try:
            contact = Contact.objects.filter(enable=True, office=self, contact_type='phone').first()
            if contact.contact_prefix:
                return '{0} {1}'.format(contact.contact_prefix, contact.contact_data)
            else:
                return contact.contact_data
        except Contact.DoesNotExist:
            return None

    def get_first_contact_by_type(self, contact_type):
        try:
            contact = Contact.objects.filter(enable=True, office=self, contact_type=contact_type).first()
            if contact.contact_prefix:
                return '{0} {1}'.format(contact.contact_prefix, contact.contact_data)
            else:
                return contact.contact_data
        except Contact.DoesNotExist:
            return None


    class Meta:
        verbose_name=_('Офис')
        verbose_name_plural = _('Офисы')
        ordering = ['order', 'city', 'name']

def preSave_Office(sender, instance, **kwargs):
    if not instance.name:
        instance.name = instance.city
    instance.url = get_unique_url_for_new_instance(instance, sender)
pre_save.connect(preSave_Office, sender=Office, dispatch_uid='pre_save_connect')


contact_type_choice = (
    ('phone', _('Телефон')),
    ('fax', _('Факс')),
    ('email', _('email')),
    ('messenger', _('Мессенджер')),
)


class Contact(BaseModel):
    contact_type = models.CharField(
        max_length=50, choices=contact_type_choice, verbose_name=_('Тип контакта'), default='phone'
    )
    contact_label = models.CharField(max_length=50, verbose_name=_('Метка контакта'), null=True, blank=True)
    contact_prefix = models.CharField(max_length=50, verbose_name=_('Префикс контакта'), null=True, blank=True)
    contact_data = models.CharField(max_length=50, verbose_name=_('Контакт'))
    office = models.ForeignKey(
        Office, verbose_name=_('Офис'), related_name='rel_contacts_for_office', on_delete=models.CASCADE)

    def __str__(self):
        if self.name:
            return self.name
        else:
            if not self.contact_prefix:
                return self.contact_label + ' ' + self.contact_data
            else:
                return self.contact_label + ' ' + self.contact_prefix + self.contact_data

    def get_prefix_w_data(self):
        if self.contact_prefix:
            return '{0} {1}'.format(self.contact_prefix, self.contact_data)
        else:
            return self.contact_data


    class Meta:
        verbose_name=_('Контакт')
        verbose_name_plural = _('Контакты')
        ordering = ['order', 'contact_type', 'contact_label']


# class FooterBlockModel(BaseModel):
#     url = models.CharField(max_length=250, verbose_name=u'URL привязанной страницы', help_text=u'адрес страницы на которую ведет данная ссылка)', null=True, blank=True)
#     enable_bullets = models.BooleanField(default=False, verbose_name='Включить метки')
#
#     def __str__(self):
#         if self.name:
#             return self.name
#         else:
#             return self.id
#
#     class Meta:
#         verbose_name=u'Блок подвала'
#         verbose_name_plural =u'Блоки подвала'
#         ordering = ['order', 'name']
#
# class FooterLinkModel(BaseModel):
#     footer_block = models.ForeignKey(FooterBlockModel,verbose_name='Блок', related_name='rel_footer_block', on_delete=models.CASCADE)
#     url = models.CharField(max_length=250, verbose_name=u'URL привязанной страницы', help_text=u'адрес страницы на которую ведет данная ссылка)', null=True, blank=True)
#
#     def __str__(self):
#         if self.name:
#             return self.name
#         else:
#             return self.id
#
#     class Meta:
#         verbose_name=u'Ссылка подвала'
#         verbose_name_plural =u'Ссылки подвала'
#         ordering = ['order', 'name']
#
#
#
# # class HeaderLinkModel(FooterLinkModel):
# #
# #     class Meta:
# #         verbose_name=u'Ссылка козырька'
# #         verbose_name_plural =u'Ссылки козырька'
# #         ordering = ['order', 'name']
#
#
# class HeaderLink(BaseModel):
#     url = models.CharField(max_length=250, verbose_name=u'URL привязанной страницы',
#                            help_text=u'адрес страницы на которую ведет данная ссылка)', null=True, blank=True)
#
#     def __str__(self):
#         if self.name:
#             return self.name
#         else:
#             return self.id
#
#     class Meta:
#         verbose_name=u'Ссылка козырька'
#         verbose_name_plural =u'Ссылки козырька'
#         ordering = ['order', 'name']