"""
Created on Jan 23, 2015

@author: noob
"""

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseNotAllowed, \
    HttpResponseRedirect, HttpResponseBadRequest
from django_yauth.decorators import yalogin_required

from common.models import CustomUserReport, Job


@yalogin_required
def add_custom_report(request):
    if request.method == 'POST':
        user = request.yauser
        job = request.GET.get('job')
        try:
            job = Job.objects.get(n=int(job))
        except (ObjectDoesNotExist, ValueError):
            return HttpResponseBadRequest('Invalid job')
        plots = [plot for plot in request.POST if plot not in ('cur_name', 'csrfmiddlewaretoken')]
        plots_json = '[' + ', '.join(['"{}"'.format(str(plot)) for plot in request.POST.keys() if
                                      plot not in ('cur_name', 'csrfmiddlewaretoken')]) + ']'
        name = request.POST.get('cur_name', '')
        cur = CustomUserReport.objects.create(
            user=user.login,
            # plots=plots,
            plots_json=plots_json,
            name='custom:{name}'.format(name=name)
        )
        redirurl = '/{job_id}#tab=custom__{cur_n}'.format(job_id=str(job.id), cur_n=cur.n)
        return HttpResponseRedirect(redirurl)
    else:
        return HttpResponseNotAllowed('')
