# -*- coding: utf-8 -*-
"""
Created on May 7, 2013

@author: noob
"""
import json
import logging

from common.models import Job
# from common.views.common import CompareJobsManager
from common.util.decorators import approve_required
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from offlinepage.views.offlinepage import Metainfo


@login_required
def jobs_offline(request, job=None):
    """
    limit can be changed from 0 to 1000
    :param request: HTTP request
    """
    logging.info('offline jobs requested')
    job = request.GET.get('job')
    if job:
        return get_offline_jobs(1, request_user=request.user, job=job)
    else:
        for_user = request.GET.get('user', '')
        limit = request.GET.get('limit', 10)
        before = request.GET.get('before')
        if before and before.isdigit():
            before = int(before)
        else:
            before = None
        try:
            if int(limit) > 1000:
                logging.warning(
                    "Limit for offline jobs passed in GET parameters is too large (%s). Limit is set to 1000", limit)
                limit = 1000
        except ValueError:
            logging.warning("Limit for offline jobs passed in GET parameters is not digital. Limit remains 10")
        logging.info('Got offline limit: %s', limit)
        if for_user.isdigit() and User.objects.filter(id=int(for_user)):
            return get_offline_jobs(int(limit), request_user=request.user, user=User.objects.get(id=int(for_user)), before=before)
        else:
            return get_offline_jobs(int(limit), request_user=request.user, before=before)


def get_offline_jobs(limit, request_user=None, user=None, job=None, before=None):
    """

    :param limit: int offline jobs query limit
    :param request_user: logged in user
    :param user: User ID
    :param job: Job Number to filter one job only (for rendering online-to-offline transition in mainpage stream)
    :param before: Job NUMBER to filter job older than this one (More button)
    """
    try:
        if job:
            jobs = [Job.check_job(Job.objects.get(n=int(job)))]
        else:
            jobs = Job.objects.exclude(td=None).order_by('-n')
            if before:
                jobs = jobs.filter(n__lt=before)
            if user:
                jobs = jobs.filter(user=user)
            jobs = jobs[:limit]

        logging.info('got offline jobs')
        data = []
        for job in jobs:
            metainfo = Metainfo(job)
            try:
                # compare_manager = CompareJobsManager(request_user.id)
                # is_in_compare = job.id in compare_manager.get_jobs()

                data.append({'person': job.user.username,
                             'user_avatar_link': metainfo.avatar_link,
                             'user_profile_link': metainfo.profile_link,
                             'user_id': job.user.id,
                             'job_number': job.n,
                             'job_name': job.name,
                             'job_dsc': job.dsc,
                             'started': job.data_started_unix,
                             'stopped': job.data_stopped_unix,
                             'project': job.project.name,
                             'flag': job.flag,
                             # 'is_in_compare': is_in_compare,
                             'port': job.srv_port,
                             'http_2': metainfo.http_codes[2],
                             'http_3': metainfo.http_codes[3],
                             'http_4': metainfo.http_codes[4],
                             'http_5': metainfo.http_codes[5],
                             'net': metainfo.net_errors,
                             'quit_status_code': job.quit_status,
                             'quit_status_text': job.quit_status_text,
                             'quit_status_text_short': job.quit_status_text.split('_')[0],
                             'duration': job.duration,
                             'cool_id': job.cool_id,
                             'cooler_id': job.cooler_id,
                             })
            except:
                continue
        return HttpResponse(json.dumps(data), content_type='application/json')
    except Job.Deleted:
        return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')
    except ValueError:
        logging.info('Job number must be digital, got %s', job)
        return HttpResponse(json.dumps([{'success': 0, 'error': 'Job number must be digital, got %s' % job}]),
                            content_type='application/json')
    except Job.DoesNotExist:
        logging.info('No jobs offline')
        return HttpResponse(json.dumps([{'success': 0, 'error': 'No jobs offline'}]), content_type='application/json')
    except Exception, exc:
        logging.exception('could not retrieve offline jobs due to:')
        return HttpResponse(json.dumps([{'success': 0, 'error': exc.__class__.__name__}]), content_type='application/json')
