from bson.objectid import ObjectId

from django.contrib.auth.decorators import permission_required, login_required
from django.core.urlresolvers import reverse
from django.http import (
    HttpResponseNotFound,
    HttpResponseServerError,
    HttpResponseRedirect,
)
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from staff.gap.controllers.templates import TemplatesCtl
from staff.gap.gap_admin.utils import (
    base_edit_template,
    base_new_template,
    edit_template_get,
    new_template_get,
)
from staff.gap.gap_admin.forms import PdfTemplateForm

import logging
logger = logging.getLogger('staff.gap.gap_admin.views.edit_pdf_template_view')


@require_http_methods(['POST', 'GET'])
@login_required
@permission_required('gap.gap_admin')
def edit_pdf_template(request, template_id=None):

    template_url = 'gap_admin/gap_templates/edit_pdf.html'

    if template_id is not None:
        context = _edit_template_get(template_id)
    else:
        context = _new_template_get()

    if request.method == 'GET':
        return render(request, template_url, {'template': context})

    form = PdfTemplateForm(request.POST)
    if form.is_valid():
        try:
            data = form.cleaned_data
            t_ctl = TemplatesCtl()
            if template_id is not None:
                template = t_ctl.find_one({'_id': ObjectId(template_id)})
                if not template:
                    return HttpResponseNotFound()
                template.update(base_edit_template(data))
                template.update(_template_data(data))
                t_ctl.update(template)
            else:
                template = base_new_template(data)
                template.update(_template_data(data))
                t_ctl.new(**template)
        except Exception:
            logger.exception('Error saving template')
            return HttpResponseServerError()

        return HttpResponseRedirect(reverse('gap-admin:list-templates'))

    return render(request, template_url, {'form': form, 'template': context})


def _edit_template_get(template_id):
    template = edit_template_get(template_id)
    if template:
        t = template['template']
        template['head'] = t['head']
        template['body_start'] = t['body_start']
        template['body_end'] = t['body_end']

    return template


def _new_template_get():
    return new_template_get('pdf', {
        'head': '.. шапка [заявления] ..',
        'body_start': '.. начало [заявления] ..',
        'body_end': '.. конец [заявления] ..',
    })


def _template_data(data):
    return {
        'template': {
            'head': data['pdf_head'],
            'body_start': data['pdf_body_start'],
            'body_end': data['pdf_body_end'],
        }
    }
