from datetime import datetime

from django.db import models
from account.models import SiteUser

from hashlib import sha512
from django.contrib.auth.hashers import check_password

from .api_errors import *


class UserToken(models.Model):
    user = models.ForeignKey(SiteUser, on_delete=models.CASCADE)
    access_token = models.CharField(max_length=128, editable=False, unique=True)
    creation_time = models.DateTimeField(default=datetime.now)

    @staticmethod
    def create_token(user: SiteUser):
        source = bytearray(user.email + user.password + str(datetime.now()), 'utf-8')
        h = sha512(source).hexdigest()

        # чекаем токен в базе
        if UserToken.objects.filter(access_token=h).count() != 0:
            # по какой-то причине есть, выкидываем исключение
            raise Exception(API_ERROR_TOKEN_CREATION)

        token = UserToken(access_token=h, user=user)
        token.save()

        print(f"created token {token.access_token[:16]}...")

        return token

    @staticmethod
    def auth(login: str, password: str):
        user = SiteUser.objects.filter(email=login)

        if len(user) == 0:
            raise Exception(API_ERROR_INVALID_LOGIN)

        if not check_password(password, user[0].password):
            raise Exception(API_ERROR_INVALID_PASSWORD)

        return user[0]

    @staticmethod
    def get_user_by_token(token: str):
        t = UserToken.objects.filter(access_token=token)

        if len(t) == 0:
            raise Exception(API_ERROR_INVALID_TOKEN)
        return t[0].user

    def __str__(self):
        return self.user.email + ": " + self.access_token[:10] + "..."
