# -*- encoding: utf-8 -*-

from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
# from django.contrib.auth.models import AbstractBaseUser

from .managers import DiscordUserOAuth2Manager


class DiscordUser(models.Model):
    """
    Represents a User authenticated with Discord OAuth2.
    """

    # Discord Attributes

    id = models.PositiveBigIntegerField(
        primary_key=True,
        help_text=_("the user's id")
    )
    username = models.CharField(
        _("username"),
        max_length=32,
        unique=True,
        help_text=_("the user's username, not unique across the platform")
    )
    global_name = models.CharField(
        _("nickname"),
        max_length=32,
        help_text=_("the user's display name, if it is set. For bots, this is the application name")
    )
    avatar = models.CharField(
        _("avatar"),
        max_length=64,
        help_text=_("the user's avatar hash")
    )
    public_flags = models.IntegerField(
        _("public flags"),
        help_text=_("the public flags on a user's account")
    )
    flags = models.IntegerField(
        _("flags"),
        help_text=_("the flags on a user's account")
    )
    locale = models.CharField(
        _("locale"),
        max_length=16,
        help_text=_("the user's chosen language option")
    )
    mfa_enabled = models.BooleanField(
        _("mfa enabled"),
        help_text=_("whether the user has two factor enabled on their account")
    )
    last_login = models.DateTimeField(
        _("last login"),
        default=timezone.now,
        help_text=_("datetime of the previous login")
    )

    # Access Token

    access_token = models.CharField(
        _("access token"),
        max_length=100,
        help_text=_("token for the application to make api calls on behalf of the user.")
    )

    # Custom Attributes

    is_active = models.BooleanField(
        _("active status"),
        default=True,
        help_text=_('Use as a "soft delete" rather than deleting the user.')
    )
    is_staff = models.BooleanField(
        _("staff status"),
        default=False,
        help_text=_("Designates whether the user can log into this admin site.")
    )
    is_superuser = models.BooleanField(
        _("superuser status"),
        default=False,
        help_text=_("Designates whether the user has unrestricted site control.")
    )

    # Object Manager

    objects = DiscordUserOAuth2Manager()

    REQUIRED_FIELDS = []
    USERNAME_FIELD = "username"

    def __str__(self):
        return self.global_name or self.username

    @property
    def avatar_url(self):
        return f"https://cdn.discordapp.com/avatars/{self.id}/{self.avatar}.webp?size=128"

    @property
    def password(self):
        return "password"

    @property
    def is_authenticated(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_username(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

    @property
    def servers(self):
        return UserServerLink.objects.filter(user_id=self.id)


class UserServerLink(models.Model):
    """
    Represents a server (aka guild) from Discord.
    Serves soley as a permissions checking table to ensure that the
    user only interacts with Subscriptions for their servers.
    """

    server_id = models.PositiveBigIntegerField()
    user = models.ForeignKey(to=DiscordUser, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    permissions = models.IntegerField()
    icon = models.CharField(
        _("icon"),
        max_length=64,
        help_text=_("the guild's icon hash"),
        null=True,
        blank=True
    )

    def __str__(self):
        return self.name

    @property
    def icon_url(self):

        if not self.icon:  # TODO: review this
            return "/static/images/placeholder-100x100.png"

        return f"https://cdn.discordapp.com/icons/{self.server_id}/{self.icon}.webp?size=80"

    # @property
    # def is_admin(self):
    #     return self.perm_flags & 0x0000000000000008

    def has_permission(self, permission):
        return self.permissions & permission
