# coding=utf-8
from __future__ import unicode_literals

import json

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 django.contrib.postgres.fields import JSONField
from BaseModels.base_models import BaseModel
from datetime import datetime


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


User.add_to_class("__str__", user_name_str)


account_type_choices = (
    ('mover', _('Перевозчик')),
    ('sender', _('Отправитель'))
)


class UserProfile(BaseModel):

    account_type = models.CharField(
        max_length=250, verbose_name=_('Тип учетной записи'), choices=account_type_choices, default='sender')

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

    avatar = models.ImageField(upload_to='uploads/', verbose_name=_('Аватар'), null=True, blank=True)

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

    phone = models.CharField(max_length=100, verbose_name=_('Телефон'), null=True, blank=True)
    country = models.CharField(max_length=250, verbose_name=_('Страна'), null=True, blank=True)
    city = models.CharField(max_length=250, verbose_name=_('Город'), null=True, blank=True)

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

    comment = models.TextField(verbose_name=_('Дополнительные сведения'), null=True, blank=True)

    creator = models.ForeignKey(
        User, verbose_name=_('Создатель'), related_name='rel_users_for_creator', null=True, blank=True,
        on_delete=models.SET_NULL
    )

    def save_user_alerts_to_session(self, request):
        for_save_to_session =  self.get_node_by_name('for_save_to_session')
        if for_save_to_session:
            for key, val in for_save_to_session.items():
                request.session[key] = val
        return request


    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:
        verbose_name = _(u'Профиль')
        verbose_name_plural = _(u'Профили')
        ordering = ('user__last_name', 'user__first_name')



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


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