from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView

from .models import Domain, Mailbox, Alias
from .owner import user_from_request


class UserLoginView(LoginView):
    template_name = 'multimail/login.html'


class DomainListView(LoginRequiredMixin, generic.ListView):
    login_url = 'login/'
    template_name = 'multimail/domains.html'
    context_object_name = 'domain_list'

    def get_queryset(self):
        """Return the last five published questions."""
        user = user_from_request(self.request)
        return Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])


class MailboxListView(LoginRequiredMixin, generic.ListView):
    login_url = 'login/'
    template_name = 'multimail/mailboxes.html'
    context_object_name = 'mailbox_list'

    def get_queryset(self):
        """Return the last five published questions."""
        user = user_from_request(self.request)
        domains = [ o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        return Mailbox.objects.filter(domain__in=domains)


class AliasListView(LoginRequiredMixin, generic.ListView):
    login_url = 'login/'
    template_name = 'multimail/aliases.html'
    context_object_name = 'alias_list'

    def get_queryset(self):
        """Return the last five published questions."""
        user = user_from_request(self.request)
        domains = [ o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        return Alias.objects.filter(source_domain__in=domains)
