from django.shortcuts import redirect
from django.views.generic import ListView
from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.views import LoginView

from .forms import mailbox_passwd
from .models import Domain, Mailbox, Alias
from .owner import user_from_request, may_own_domain


class MayOwnDomainMixin(UserPassesTestMixin):

    def test_func(self):
        return may_own_domain(self.request.user)

    def handle_no_permission(self):
        return redirect('multimail:login')


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


class IndexView(MayOwnDomainMixin, ListView):
    login_url = 'login/'
    template_name = 'multimail/index.html'
    context_object_name = 'domain_list'

    def fill_related(self, domains):
        for domain in domains:
            domain.mailboxes = Mailbox.objects.filter(domain=domain)
            domain.aliases = Alias.objects.filter(source_domain=domain)
            yield domain

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


def dispatchIndex(request):
    if may_own_domain(request.user):
        return IndexView.as_view()(request)
    else:
        return mailbox_passwd(request)


class DomainListView(MayOwnDomainMixin, 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(MayOwnDomainMixin, 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(MayOwnDomainMixin, 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)
