from django import forms
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import permission_required
from django_mako_plus.controller import view_function
from .. import dmp_render, dmp_render_to_response

from catalog.models import Venue

##
# Show
#
@view_function
def process_request(request):
    venues = Venue.objects.all()

    template_vars = {
        'venues' : venues,
    }

    return dmp_render_to_response(request, 'venues.show.html', template_vars)



##
# Create
#
@view_function
@permission_required('catalog.add_venue', login_url='/homepage/index/')
def new(request):
    form = CreateVenueForm(request.POST or None)

    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/catalog/venues/')

    template_vars = {
        'form' : form
    }

    return dmp_render_to_response(request, 'venues.new.html', template_vars)

class CreateVenueForm(forms.ModelForm):
    class Meta:
        model = Venue
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(CreateVenueForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget = forms.TextInput(attrs = {
                'class' : 'form-control'
            })



##
# Edit
#
@view_function
@permission_required('catalog.change_venue', login_url='/homepage/index/')
def edit(request):
    try:
        venue = Venue.objects.get(id=request.urlparams[0])
    except Venue.DoesNotExist:
        return HttpResponseRedirect('/catalog/venues/')

    form = EditVenueForm(request.POST or None, instance=venue)

    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/catalog/venues.edit/%i' % venue.id)

    template_vars = {
        'venue' : venue,
        'form' : form,
    }

    return dmp_render_to_response(request, 'venues.edit.html', template_vars)

class EditVenueForm(forms.ModelForm):
    class Meta:
        model = Venue
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(EditVenueForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget = forms.TextInput(attrs = {
                'class' : 'form-control'
            })



##
# Delete
#
@view_function
@permission_required('catalog.delete_venue', login_url='/homepage/index/')
def delete(request):
    try:
        venue = Venue.objects.get(id=request.urlparams[0])
    except Venue.DoesNotExist:
        return HttpResponseRedirect('/catalog/venues/')

    venue.delete()

    return HttpResponseRedirect('/catalog/venues/')
