# -*- coding: utf-8 -*-
"""
Created on Aug 17, 2016

@author: noob
"""

from .base import Api
from common.models import Job
from django.contrib.auth.models import User
import logging


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

    http_method_names = ['get']

    def get(self, request):
        """
        limit can be changed from 0 to 1000
        :param request: HTTP request
        """
        limit = request.GET.get('limit', 10)
        try:
            if int(limit) > 1000:
                limit = 1000
        except ValueError:
            logging.warning("Limit for queued jobs passed in GET parameters is not digital. Limit remains 10")
        user = request.GET.get('user')
        return self.queued_jobs(int(limit), user=user)

    @staticmethod
    def queued_jobs(limit, user=None):
        """
        gets queued jobs data
        :param limit: int
        :param user: string user login
        """
        try:
            if user:
                User.objects.get(username=user)
            jobs_queued = Job.objects.filter(td__isnull=True, status__regex='(queued|configure.*|prepare.*|start)')
            if user:
                jobs_queued = jobs_queued.filter(person=user)
            resp = []
            for job in jobs_queued[:limit]:
                resp.append({'person': job.person,
                             'n': job.n,
                             'name': job.name,
                             'started': job.fd.strftime('%Y-%m-%d %H:%M:%S'),
                             #                      'estimated_duration':job.estimated_duration,
                             'task': job.task,
                             'tank': job.tank_reduced or '',
                             'target': job.srv_reduced or '',
                             'port': job.srv_port,
                             'status': job.status,
                             })
            return resp
        except User.DoesNotExist:
            return [{'success': 0, 'error': 'Unknown user {}'.format(user)}]
        except Job.DoesNotExist:
            return [{'success': 0, 'error': 'No jobs queued'}]
        except Exception as exc:
            logging.exception('could not retrieve queued jobs due to:')
            return [{'success': 0, 'error': exc.__class__.__name__}]
