from django.contrib.auth.decorators import login_required
from django.forms import ModelForm
from django.forms.utils import ErrorList
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render
from django.db import IntegrityError

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


class DomainForm(ModelForm):
    class Meta:
        model = Domain
        fields = '__all__'
        # fields = ['domain']


class MailboxForm(ModelForm):
    class Meta:
        model = Mailbox
        fields = '__all__'


class AliasForm(ModelForm):
    class Meta:
        model = Alias
        fields = '__all__'


@login_required(login_url='/login/')
def edit_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
    if request.method == 'POST':
        form = DomainForm(request.POST, instance=domain)
        try:
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/domains/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = DomainForm(instance=domain)

    return render(request, 'multimail/edit.html', {'form': form})


@login_required(login_url='/login/')
def new_domain(request):
    user = user_from_request(request)
    if request.method == 'POST':
        form = DomainForm(request.POST)
        try:
            if form.is_valid():
                domain = form.save()
                domain.admin.create(admin=user['name'], source=user['source'])
                return HttpResponseRedirect('/domains/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = DomainForm()

    return render(request, 'multimail/edit.html', {'form': form})


@login_required(login_url='/login/')
def edit_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
    if request.method == 'POST':
        form = MailboxForm(request.POST, instance=mailbox)
        try:
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/mailboxes/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = MailboxForm(instance=mailbox)

    return render(request, 'multimail/edit.html', {'form': form})


@login_required(login_url='/login/')
def new_mailbox(request):
    if request.method == 'POST':
        user = user_from_request(request)
        domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        form = MailboxForm(request.POST)
        try:
            if form.is_valid() and form.domain in domains:
                form.save()
                return HttpResponseRedirect('/mailboxes/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = MailboxForm()

    return render(request, 'multimail/edit.html', {'form': form})


@login_required(login_url='/login/')
def edit_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
    if request.method == 'POST':
        form = AliasForm(request.POST, instance=alias)
        try:
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/aliases/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = AliasForm(instance=alias)

    return render(request, 'multimail/edit.html', {'form': form})


@login_required(login_url='/login/')
def new_alias(request):
    if request.method == 'POST':
        user = user_from_request(request)
        domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
        form = AliasForm(request.POST)
        try:
            if form.is_valid() and form.source_domain in domains:
                form.save()
                return HttpResponseRedirect('/aliases/')

        except IntegrityError as e:
            form.add_error(None, e)

    else:
        form = AliasForm()

    return render(request, 'multimail/edit.html', {'form': form})
