from django.utils import timezone
from common.headers import *
from app.models import *

VALIDATION_FAILED = L('Form validation failed.')

def urlpatterns():
    return patterns('',
                    url('^list/$', get_list),
                    url('^add/$', add),
                    url('^item:(?P<pk>.*)/$', item),
    )

@require_GET
def get_list(request):
    polls = map(lambda p: p.as_json(), Poll.objects.order_by('-pub_date'))
    return JsonResponse(polls)

@require_POST
def add(request):
    data = json.loads(request.body)
    isValid = True
    error = {}
    poll_data = Poll().as_json()
    poll_data.update({
        'question': data.get('question'),
        'pub_date': timezone.now(),
    })
    poll_form = PollForm(poll_data)
    poll_instance = poll_form.instance
    isValid = isValid and poll_form.is_valid()
    error.update(poll_form.errors)

    error['choices'] = []
    choices_instances = []
    for choice in data['choices']:
        choice_data = Choice().as_json()
        choice_data.update(choice)
        choice_form = ChoiceForm(choice_data)
        choices_instances.append(choice_form.instance)
        isValid = isValid and choice_form.is_valid()
        error['choices'].append(choice_form.errors)
    if not isValid:
        print error
        return JsonResponse(error, app_notify=VALIDATION_FAILED, status=400)
    else:
        poll_instance.save()
        for c in choices_instances:
            c.poll = poll_instance
            c.save()
        msg = L("Poll added as #%s.") % poll_instance.pk
        return HttpResponse(app_notify=msg)

def item(request, pk):
    p = get_object_or_404(Poll, pk=pk)
    if request.method == 'GET':
        return JsonResponse(p.as_json())
    elif request.method == 'POST':
        data = json.loads(request.body)
        isValid = True
        error = {}
        #poll_data = Poll().as_json()
        #poll_data.update({
        ##    'question': data.get('question'),
        #    'pub_date': timezone.now(),
        #})
        poll_data = data
        poll_data['pub_date'] = timezone.now()
        poll_form = PollForm(poll_data, instance=p)
        poll_instance = poll_form.instance
        isValid = isValid and poll_form.is_valid()
        error.update(poll_form.errors)

        error['choices'] = []
        choices_instances = []
        for choice in data['choices']:
            cpk = choice.get('pk')
            choice_data = choice
            if cpk is not None:
                # old choice
                c = Choice.objects.get(pk=choice['pk'])
                choice_form = ChoiceForm(choice_data, instance=c)
            else:
                choice_form = ChoiceForm(choice_data)
            choices_instances.append(choice_form.instance)
            isValid = isValid and choice_form.is_valid()
            error['choices'].append(choice_form.errors)
        if not isValid:
            return JsonResponse(error, app_notify=VALIDATION_FAILED, status=400)
        else:
            poll_instance.save()
            for c in choices_instances:
                c.poll = poll_instance
                c.save()
            msg = L("Poll #%s edited successfully.") % poll_instance.pk
            return HttpResponse(app_notify=msg)

    elif request.method == 'DELETE':
        p.delete()
        msg = L("Poll #%s deleted.") % pk
        return HttpResponse(app_notify=msg)
