"""
Created on Jan 23, 2015

@author: noob
"""
import json
from common.models import CustomUserReport, Job
from common.util.decorators import approve_required
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotAllowed, \
    HttpResponseRedirect, HttpResponseBadRequest


@login_required
@approve_required
def add_custom_report(request):
    if request.method == 'POST':
        user = request.user
        job = request.GET.get('job')
        try:
            job = Job.check_job(Job.objects.get(n=int(job)))
        except Job.Deleted:
            return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')
        except (Job.DoesNotExist, ValueError):
            return HttpResponseBadRequest('Invalid job')
        plots_json = '['+', '.join(['"%s"' % str(plot) for plot in request.POST.keys() if plot not in ('cur_name', 'csrfmiddlewaretoken')]) + ']'
        name = request.POST.get('cur_name', '')
        cur = CustomUserReport(user=user.username, plots_json=plots_json, name='custom:' + name)
        cur.save()
        redirurl = '/' + str(job.id) + r'#tab=custom__' + str(cur.n)
        return HttpResponseRedirect(redirurl)
    else:
        return HttpResponseNotAllowed(['POST'])
