from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from nameserver.models import Nameserver, NameserverForm

# Create your views here.
def index(request):
    nameserver_list = Nameserver.objects.all().order_by('hostname')[:10]
    paginator = Paginator(nameserver_list, 10)

    page = request.GET.get('page')

    try:
        nameservers = paginator.page(page)
    except PageNotAnInteger:
        nameservers = paginator.page(1)
    except EmptyPage:
        nameservers = paginator.page(paginator.num_pages)

    return render( request, 'nameserver/index.html', {
        'nameservers': nameservers,
    })

def add(request):
    if request.method == 'POST':
        form = NameserverForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/nameserver/')
    else:
        form = NameserverForm()

    return render( request, 'nameserver/add.html', {
        'form': form,
    })

def delete(request, nameserver_id):
    try:
        nameserver = Nameserver.objects.get(pk=nameserver_id)
    except Nameserver.DoesNotExist:
        raise Http404

    nameserver.delete()
    return HttpResponseRedirect('/nameserver/')
