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

@author: noob
"""

from .base import Api
from django.contrib.auth.models import User
from django.db import connections
import logging
import settings


class JobsOnline(Api):
    """
    retrieves current jobs rendered by API
    """

    http_method_names = ['get']

    def get(self, request):
        """
        :param request: HTTP request
        """
        limit = request.GET.get('limit', 10)
        if settings.ENV_TYPE == "production":
            later_than = request.GET.get('later_than', 1680000)
        else:
            later_than = request.GET.get('later_than', 1510000)
        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")
        user = request.GET.get('user')
        return self.online_jobs(int(limit), later_than, user=user)

    @staticmethod
    def online_jobs(limit, later_than, user=None):
        """
        gets online jobs data
        limit can be changed from 0 to 1000
        :param limit: online jobs query limit, passed as GET parameter
        :param later_than: Job NUMBER to select jobs with numbers higher than this only
        :param user: string user login, passed as GET parameter
        """
        try:
            if user:
                User.objects.get(username=user)
            resp = []
            query_params = {'limit': limit,
                            'later_than': later_than}
            sql = '''select n
                    from job 
                    where n > %(later_than)s 
                    and td is NULL
                    '''
            if user:
                sql += ' and person=%(user)s'
                query_params['user'] = user
            sql += ' limit %(limit)s;'
            cursor = connections['default'].cursor()
            try:
                cursor.execute(sql, query_params)
                jobs_online = cursor.fetchall()
                resp = [{'n': j[0]} for j in jobs_online]
            except:
                logging.exception('')
            finally:
                cursor.close()
            return resp
        except User.DoesNotExist:
            return [{'success': 0, 'error': 'Unknown user {}'.format(user)}]
        except Exception as exc:
            logging.exception('could not retrieve online jobs due to:')
            return [{'success': 0, 'error': exc.__class__.__name__}]
