from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone

from konova.utils.generators import generate_token


class APIUserToken(models.Model):
    token = models.CharField(
        primary_key=True,
        max_length=1000,
        default=generate_token,
    )
    valid_until = models.DateField(
        blank=True,
        null=True,
        help_text="Token is only valid until this date",
    )
    is_active = models.BooleanField(
        default=False,
        help_text="Must be activated by an admin"
    )

    def __str__(self):
        return self.token

    @staticmethod
    def get_user_from_token(token: str, username: str):
        """ Getter for the related user object

        Args:
            token (str): The used token
            username (str): The username

        Returns:
            user (User): Otherwise None
        """
        _today = timezone.now().date()
        try:
            token_obj = APIUserToken.objects.get(
                token=token,
                user__username=username
            )
            if not token_obj.is_active:
                raise PermissionError("Token unverified")
            if token_obj.valid_until is not None and token_obj.valid_until < _today:
                raise PermissionError("Token validity expired")
        except ObjectDoesNotExist:
            raise PermissionError("Credentials invalid")
        return token_obj.user
