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

@author: noob
"""

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


class JobsOffline(Api):
    """
    retrieves offline jobs rendered by API
    """

    http_method_names = ['get']

    def get(self, request, limit=10):
        """
        limit can be changed from 0 to 1000
        :param request: HTTP request
        :param limit: offline jobs query limit, passed as GET parameter
        """
        job = request.GET.get('job')
        if job:
            return self.get_offline_jobs(int(limit), job=job)
        else:
            user = request.GET.get('user')
            limit = request.GET.get('limit', 10)
            try:
                if int(limit) > 1000:
                    logging.warning(
                        "Limit for offline jobs passed in GET parameters is too large ({}). Limit is set to 1000"
                        .format(limit))
                    limit = 1000
            except ValueError:
                logging.warning("Limit for offline jobs passed in GET parameters is not digital. Limit remains 10")
            if user:
                return self.get_offline_jobs(int(limit), user=user)
            else:
                return self.get_offline_jobs(int(limit))

    @staticmethod
    def get_offline_jobs(limit, user=None, job=None):
        """

        :param limit: int offline jobs query limit
        :param user: str
        :param job: Job NUMBER
        """
        try:
            if user:
                User.objects.get(username=user)
                jobs_offline = Job.objects.filter(person=user).exclude(td=None).order_by('-n')[:limit]
            elif job:
                jobs_offline = [Job.objects.get(n=int(job))]
                jobs_offline = [j for j in jobs_offline if jobs_offline[0].td is not None]
            else:
                jobs_offline = Job.objects.exclude(td=None).order_by('-n')[:limit]
            data = []
            for job in jobs_offline:
                try:
                    data.append({'person': job.person,
                                 'n': job.n,
                                 'name': job.name,
                                 'started': job.data_started_unix,
                                 'stopped': job.data_stopped_unix,
                                 'task': job.task,
                                 'tank': job.tank_reduced,
                                 'target': job.srv_reduced,
                                 'port': job.srv_port,
                                 'quit_status': job.quit_status,
                                 # quit_status_text': job.quit_status_text,
                                 # 'quit_status_text_short': job.quit_status_text.split('_')[0],
                                 'duration': job.duration,
                                 })
                except:
                    continue
            return data
        except ValueError:
            return [{'success': 0, 'error': 'Job number must be digital, got {}'.format(job)}]
        except User.DoesNotExist:
            return [{'success': 0, 'error': 'Unknown user {}'.format(user)}]
        except Job.DoesNotExist:
            return [{'success': 0, 'error': 'Invalid job number'}]
        except Exception as exc:
            logging.exception('could not retrieve offline jobs due to:')
            return [{'success': 0, 'error': exc.__class__.__name__}]
