from .base import Api
from common.models import Component
from django.http import Http404
from django.db.models import Q
from collections import OrderedDict
import logging


class RegressComponentList(Api):
    @staticmethod
    def get(request, *args):
        order = request.GET.get('order', '')
        if 'service' not in list(request.GET.keys()):
            service = None
        else:
            service = request.GET['service']
        if service:
            components = Component.objects.exclude(services_json__isnull=True).exclude(services_json__in=['', '[]'])
            if order:
                components = components.order_by(order)
            components = components.order_by('name')
            components = [c for c in components if service in c.services]
        elif service is None:
            components = Component.objects.filter(tag=args[0].upper())
            if order:
                components = components.order_by(order)
            components = components.order_by('name')
        else:
            components = Component.objects\
                .filter(tag=args[0].upper())\
                .filter(Q(services_json__in=('', '[]')) | Q(services_json__isnull=True))
            if order:
                components = components.order_by(order)
            components = components.order_by('name')

        if not components:
            raise Http404('Regression components not found')

        res = []
        for component in components:
            try:
                res.append(OrderedDict([
                    ('n', component.n),
                    ('name', component.name),
                    ('services', component.services),
                    ('dsc', component.dsc if component.dsc else ''),
                    ('project', component.tag),
                    ('tag', component.tag),
                ]))
            except:
                logging.exception('')

        return res

