from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.contrib import messages
from django.conf import settings

from reportmonster.classes.vessel import Vessel

from bcrypt import checkpw


class ReportMonsterBackend(ModelBackend):
    def authenticate(self, request, username: str = None, password: str = None):
        self.request = request

        monster = settings.MONSTERCONFIG
        loginvessel = list(
            filter(lambda x: x.name == settings.LOGIN_VESSEL, monster.vessels)
        )[0]

        userdata = list(loginvessel.getUsers(username=username).values())[0]

        if checkpw(password.encode(), userdata["password"].encode()):
            user, _ = get_user_model().objects.get_or_create(email=username)
            user.save()
            return user
