# coding=utf-8
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import post_save, pre_save
from django.contrib.contenttypes.fields import GenericRelation
from BaseModels.base_models import BaseModel
from datetime import datetime
from django.conf import settings




def user_name_str(self):
    return f'{self.last_name} {self.first_name}'


User.add_to_class("__str__", user_name_str)


class UserProfile(BaseModel):

    user = models.OneToOneField(User, verbose_name=_('Пользователь'), related_name=u'user_profile',
                                null=True, blank=True, on_delete=models.CASCADE)

    UI_lang = models.CharField(max_length=2, verbose_name=_('Язык интерфейса'), choices=settings.LANGUAGES)

    nick_name = models.CharField(max_length=250, verbose_name=_('Псевдоним'), null=True, blank=True)

    authCode = models.CharField(max_length=32, null=True, blank=True)

    phone = models.CharField(max_length=100, verbose_name=_('Телефон'), null=True, blank=True)

    birthdate = models.DateField(verbose_name=_(u'Дата рождения'), null=True, blank=True)

    comment = models.TextField(verbose_name=_('Комментарий'), null=True, blank=True)

    referal_link = models.TextField(verbose_name=_('Реферальная ссылка'))
    balance = models.FloatField(verbose_name=_('Баланс'), default=0)
    questions_count = models.IntegerField(verbose_name=_('Задано вопросов'), default=0)
    answer_success_count = models.IntegerField(verbose_name=_('Успешных ответов'), default=0)


    def __str__(self):
        if self.user:
            return '{0} {1}'.format(self.user.last_name, self.user.first_name)
        else:
            return str(self.id)


    class Meta:
        permissions = (

        )

        verbose_name = _('Профиль')
        verbose_name_plural = _('Профили')
        ordering = ('user__last_name', 'user__first_name')



# @receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)


post_save.connect(create_user_profile, sender=User, dispatch_uid='post_save_connect')


# @receiver(pre_save, sender=User)
def preSaveUser(sender, instance, **kwargs):
    if not instance.email:
        instance.email = str(instance.username).lower()

    try:
        instance.user_profile.modifiedDT = datetime.now()
    except:
        pass


pre_save.connect(preSaveUser, sender=User, dispatch_uid='pre_save_connect')
