import json

from django.contrib.auth.decorators import login_required, permission_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.decorators.http import require_POST


from staff.gap.controllers.templates import TemplatesCtl

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


@require_POST
@login_required
@permission_required('gap.gap_admin')
def import_templates(request):
    recreate = bool(request.POST.get('recreate'))
    templates_file = request.FILES.get('templates_file')
    templates = [json.loads(t) for t in templates_file.readlines()]
    ctl = TemplatesCtl()
    if recreate:
        ctl.recreate_collection()
    for t_dict in templates:
        ctl.new(**t_dict)

    return HttpResponseRedirect(reverse('gap-admin:index'))
