from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rowers.views.statements import *

from rq import Queue
from redis import Redis
from rq.job import Job

@login_required()
def failed_queue_view(request):
    if not request.user.is_staff:
        raise PermissionDenied("Not Allowed")

    q = Queue('failed', connection=Redis())

    resultslist = []

    for job in q.jobs:
        traceback = str(job.exc_info)


        info = {
            'id':job.id,
            'started_at': job.started_at,
            'traceback1': traceback,
            }


        resultslist += [info]


    return render(request,
                  "failed_jobs.html",
                  {
                      'resultslist':resultslist,
                      }
                  )

@login_required()
def failed_queue_empty(request):
    if not request.user.is_staff:
        raise PermissionDenied("Not Allowed")

    q = Queue('failed', connection=Redis())

    q.empty()

    return HttpResponseRedirect(reverse('failed_queue_view'))


@login_required()
def failed_job_view(request,id=0):
    if not request.user.is_staff:
        raise PermissionDenied("Not Allowed")

    q = Queue('failed', connection=Redis())
    thejob = q.fetch_job(id)

    thejob.delete()

    return HttpResponseRedirect(reverse('failed_queue_view'))


@login_required()
def errormessage_view(request,errormessage='aap'):
    if (errormessage=='3dsecure'):
        errormessage = '3D Secure Card Verification Error. Please check your card details.'
    messages.error(request,errormessage)

    return JSONResponse({
        "result":1,
        })


# Shows analysis page
@login_required()
@permission_required('rower.is_coach',fn=get_user_by_userid,raise_exception=True)
def analysis_view(request,userid=0):
    r = getrequestrower(request,userid=userid)
    return render(request,
                  "analysis.html",
                  {
                      'active':'nav-analysis',
                      'rower':r,
                  }
                  )

# Shows laboratory page
@login_required()
@permission_required('rower.is_coach',fn=get_user_by_userid,raise_exception=True)
def laboratory_view(request,userid=0):
    r = getrequestrower(request,userid=userid)
    return render(request,
                  "laboratory.html",
                  {
                      'active':'nav-analysis',
                      'rower':r,
                  }
                  )
