from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import logout as auth_logout

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


@user_passes_test(may_own_domain, login_url='/login/')
def delete_domain(request, domain_id):
    try:
        user = user_from_request(request)
        domain = Domain.objects.filter(admin__admin=user['name'], admin__source=user['source']).get(pk=domain_id)
    except:
        raise Http404
    # TODO this might fail due to foreign key constraint
    domain.delete()
    return HttpResponseRedirect(reverse('multimail:domains'))


@user_passes_test(may_own_domain, login_url='/login/')
def delete_mailbox(request, mailbox_id):
    try:
        user = user_from_request(request)
        domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        mailbox = Mailbox.objects.filter(domain__in=domains).get(pk=mailbox_id)
    except:
        raise Http404
    mailbox.delete()
    return HttpResponseRedirect(reverse('multimail:mailboxes'))


@user_passes_test(may_own_domain, login_url='/login/')
def delete_alias(request, alias_id):
    try:
        user = user_from_request(request)
        domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        alias = Alias.objects.filter(source_domain__in=domains).get(pk=alias_id)
    except:
        raise Http404
    alias.delete()
    return HttpResponseRedirect(reverse('multimail:aliases'))


def logout(request):
    auth_logout(request)
    return HttpResponseRedirect(reverse('multimail:login'))
