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

from customer.models import Customer, CustomerForm
from event.models import LogEvent

# Create your views here.
def index(request):
    customer_list = Customer.objects.all().order_by('name')[:10]
    paginator = Paginator(customer_list, 10)
    
    page = request.GET.get('page')
    
    try:
        customers = paginator.page(page)
    except PageNotAnInteger:
        customers = paginator.page(1)
    except EmptyPage:
        customers = paginator.page(paginator.num_pages)
    
    return render( request, 'customer/index.html', {
        'customers': customers,
    })

def add(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            new_customer = form.save()
            e = LogEvent(subject = 'customer', author = 'me', action = ('create %s' % new_customer.name) , created_at = timezone.now())
            e.save()
            return HttpResponseRedirect('/customer/')
    else:
        form = CustomerForm()

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

def edit(request, customer_id):
    try:
        customer = Customer.objects.get(pk=customer_id)
    except Customer.DoesNotExist:
        raise Http404

    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            customer = form.save()
            e = LogEvent(subject = 'customer', author = 'me', action = ('edit %s' % customer.name) , created_at = timezone.now())
            e.save()
            return HttpResponseRedirect('/customer/')
    else:
        form = CustomerForm(instance=customer)

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

def delete(request, customer_id):
    try:
        customer = Customer.objects.get(pk=customer_id)
    except Customer.DoesNotExist:
        raise Http404

    e = LogEvent(subject = 'customer', author = 'me', action = ('delete %s' % customer.name) , created_at = timezone.now())
    e.save()
    customer.delete()
    return HttpResponseRedirect('/customer/')
