# -*- coding: utf-8 -*-
"""
Created on Nov 22, 2016

@author: noob
"""
from django.http.response import HttpResponse
from mobilecompare.models import CompareMobileJobsManager
from mobilepage.models import MobileJob
from django_yauth.decorators import yalogin_required
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import json


@yalogin_required
def is_mobile_present(request, task_key):
    return HttpResponse(json.dumps(bool(MobileJob.objects.filter(task=task_key.upper()))),
                        RequestContext(request))


@yalogin_required
def render_mobile_block(request, task_key):
    task_key = task_key.upper()
    user = request.yauser
    manager = CompareMobileJobsManager(user.login)
    compare_jobs = manager.get_jobs()
    jobs = MobileJob.objects.filter(task=task_key).order_by('-n')[:50]
    return render_to_response('mobile_block.html', {
        'jobs': jobs,
        'task': task_key,
        'is_in_compare': {j.id: bool(j.n in compare_jobs) for j in jobs},
    }, RequestContext(request))


@yalogin_required
def more_jobs(request, task_key):
    task_key = task_key.upper()
    user = request.yauser
    limit = request.GET.get('limit', '30')
    before = request.GET.get('before')
    if limit.isdigit():
        limit = int(limit)
    else:
        limit = 30
    jobs = MobileJob.objects.filter(task=task_key)
    if before:
        jobs = jobs.filter(n__lt=before)
    jobs = jobs.order_by('-n')[:limit]
    manager = CompareMobileJobsManager(user.login)
    compare_jobs = manager.get_jobs()
    return HttpResponse(json.dumps([{'n': job.n,
                                     'name': job.name,
                                     'task': job.task,
                                     'flag': job.flag,
                                     'is_in_compare': bool(job.n in compare_jobs)}
                                    for job in jobs]
                                   ), content_type='application/json'
                        )
