# -*- coding: utf-8 -*-
"""
Created on Apr 5, 2013

@author: noob
"""

from common.models import Job
from common.util.decorators import approve_required
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import ProgrammingError
from django.db.utils import OperationalError
from django.http import HttpResponse
from json import dumps
from offlinepage.views.offlinepage import Metainfo
import logging


@login_required
def jobs_online(request, limit=10):
    """
    limit can be changed from 0 to 1000
    :param request: HTTP request
    :param limit: online jobs query limit, passed as GET parameter
    """
    logging.debug('online jobs requested')
    limit = request.GET.get('limit', 10)
    try:
        if int(limit) > 1000:
            limit = 1000
    except ValueError:
        logging.warning("Limit for online jobs passed in GET parameters is not digital. Limit remains 10")
    logging.info('Got online limit: %s', limit)
    for_user = request.GET.get('user', '')

    if for_user.isdigit() and User.objects.filter(id=int(for_user)):
        return online_jobs(int(limit), user=User.objects.get(id=int(for_user)))
    else:
        return online_jobs(int(limit))


def online_jobs(limit, user=None):
    """
    gets online jobs data
    :param limit: int
    :param user: string user login, passed as GET parameter
    """
    try:
        jobs = Job.objects.filter(td=None)
        if user:
            jobs = jobs.filter(user=user)
        jobs = jobs.order_by('-n')[:limit]
        resp = []
        for job in jobs:
            metainfo = Metainfo(job)
            try:
                resp.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,
                             'estimated_duration': job.estimated_duration,
                             'project': job.project.name,
                             'port': job.srv_port,
                             'cool_id': job.cool_id,
                             'cooler_id': job.cooler_id,
                             })
            except (OperationalError, ProgrammingError), e:
                logging.info('Job %s DB error %s', job.n, e.message)
                continue
            except Exception as e:
                logging.error('online jobs Job %s error %s', job.n, e.message)
                continue
        return HttpResponse(dumps(resp), content_type='application/json')
    except ObjectDoesNotExist:
        logging.info('No jobs online')
        return HttpResponse(dumps([{'success': 0, 'error': 'No jobs online'}]), content_type='application/json')
    except Exception, exc:
        logging.exception('could not retrieve online jobs due to:')
        return HttpResponse(dumps([{'success': 0, 'error': exc.__class__.__name__}]), content_type='application/json')
