from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy


class DashboardLayout(models.Model):
    """ Dashboard widgets layout for one user """
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             verbose_name=gettext_lazy('User'),
                             help_text=gettext_lazy('Owner of dashboard'))
    widgets = models.JSONField(help_text=gettext_lazy('Widgets'), default=dict)

    def __str__(self):
        return f'{self.pk} {self.user.username}'


@receiver(post_save, sender=User)
def add_dashboard_layout(sender, **kwargs):
    """ Add dashboard layout to new user """
    user = kwargs['instance']
    layout = DashboardLayout.objects.filter(user=user)

    if not layout:
        layout = DashboardLayout(user=user, widgets={})
        layout.save()
