from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import AbstractUser
import re

from multimail.models import Mailbox


class MailUser(AbstractUser):
    def __init__(self, *args, **kwargs):
        m = kwargs['mailbox']
        super().__init__(username=m.username+"@"+m.domain)
        self.id = m.id
        self.mailbox = m

    def is_active(self):
        return True

    def is_authenticated(self):
        return True

    def save(self, *args, **kwargs):
        pass


class MailboxBackend(BaseBackend):

    def authenticate(self, request, **kwargs):
        m = re.match("([^@]+)@([^@]+)", kwargs['username'])
        if not m:
            return None
        username, domain = m.groups()
        password = kwargs['password']
        try:
            mailbox = Mailbox.objects.get(username=username, domain=domain)
            if mailbox.check_password(password) is True:
                return MailUser(mailbox=mailbox)
            else:
                return None
        except Mailbox.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            mailbox = Mailbox.objects.get(pk=user_id)
            return MailUser(mailbox=mailbox)
        except Mailbox.DoesNotExist:
            return None