# -*- coding: utf-8 -*-
from __future__ import annotations

from django.contrib.auth.models import (
    AbstractUser,
    Group,
    Permission,
    UserManager,
)
from django.db import models
from django.utils.translation import gettext_lazy as _
import uuid6


class ActiveAccountsManager(models.Manager):
    def get_queryset(self) -> models.QuerySet:
        return super().get_queryset().filter(
            is_active=True,
            is_staff=False,
        )


class Account(AbstractUser):
    id = models.UUIDField(
        null=False, blank=False, default=uuid6.uuid7, primary_key=True,
    )
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            (
                'The groups this user belongs to. A user will get all '
                'permissions granted to each of their groups.'
            ),
        ),
        related_name='account_set',
        related_query_name='account',
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name='account_set',
        related_query_name='account',
    )
    raw_settings = models.JSONField(default=dict, db_column='settings')
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()
    active_accounts = ActiveAccountsManager()

    class Meta:
        verbose_name = _('Account')
        verbose_name_plural = _('Accounts')

    def __str__(self) -> str:
        return f'<Account pk={self.pk} username={self.username}>'

    @property
    def settings(self) -> dict:
        result = {**self.raw_settings}

        auto_load_embeds = result.get('auto_load_embeds', None)
        if isinstance(auto_load_embeds, str) is True:
            result['auto_load_embeds'] = (auto_load_embeds == 'True')
        else:
            result['auto_load_embeds'] = auto_load_embeds

        light_mode = result.get('light_mode', None)
        if isinstance(light_mode, str) is True:
            result['light_mode'] = (light_mode == 'True')
        else:
            result['light_mode'] = light_mode

        return result
