import json
import logging

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

from staff.gap.controllers.gap_settings import GapSettingsCtl


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


@require_http_methods(['POST', 'GET'])
@login_required
@permission_required('gap.gap_admin')
def workflow_files_settings(request):
    template_url = 'gap_admin/gap_settings/edit_workflow_files.html'

    if request.method == 'GET':
        context = {
            'workflow_files': json.dumps(GapSettingsCtl().get_workflow_files(), indent=4),
        }
        return render(request, template_url, context)

    try:
        json_data = request.POST.get('workflow_files', '[]')
        data = json.loads('{"settings": %s}' % json_data)
        GapSettingsCtl().update_workflow_files(data['settings'])
    except Exception:
        logger.exception('Error saving template')
        return HttpResponseServerError()

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