from .base import ApiTask, Http400
from common.models import Job
from django.http import Http404
from collections import OrderedDict


class TaskJobList(ApiTask):
    """
    retrieves jobs for task rendered by API
    """

    @staticmethod
    def get(request, task):
        """
        :param request: HTTP request
        :param task: task object passed from request
        """
        if task is None:
            raise Http404('Task not found')
        fields = request.GET.get('fields', 'n')
        full = request.GET.get('full', '')
        order_by = request.GET.get('order_by', 'n')
        if full:
            fields = 'n,fd,td,person,name,dsc,flag,status,command_line,ammo_path,loop_cnt,quit_status,component,ver'
        fields = fields.split(',')
        rules = {
            'n': lambda j: j.n,
            'fd': lambda j: str(j.fd),
            'td': lambda j: str(j.td),
            'person': lambda j: j.person,
            'name': lambda j: j.name,
            'dsc': lambda j: j.dsc,
            'flag': lambda j: j.flag,
            'command_line': lambda j: j.command_line,
            'ammo_path': lambda j: j.ammo_path,
            'loop_cnt': lambda j:
            round((j.loop_cnt if j.loop_cnt is not None else 0), 2),
            'quit_status': lambda j: j.quit_status,
            'status': lambda j: j.status,
            'component': lambda j: j.component,
            'ver': lambda j: j.ver if j.ver else ''
        }

        for field in fields:
            if field not in rules:
                raise Http400('Field {} not found'.format(field))

        res = []
        for job in Job.objects.filter(task=task).order_by(order_by):
            res.append(OrderedDict(
                (col, rules[col](job)) for col in fields
            ))
        return res
