# -*- coding: UTF-8 -*-

from django.db.models import Q, Count
from gm_dataquery.dataquery import DataBuilder
from gm_dataquery.dataquery import DataSQLQuery
from gm_dataquery.db import DB

from hippo.models import TrafficStat, StatDoctorDaily
from themis.models import Team


class TeamDB(DataBuilder):
    def getval_recursive_team(self, obj):
        return list(set([x.id for x in obj.all_children_team]))

    def getval_recursive_user(self, obj):
        users = [x.id for x in obj.team_user.all()]
        childred_users = [x.id for x in obj.all_children_user]
        return list(set(users + childred_users))

    def getval_subteams(self, obj):
        return [x.id for x in obj.subteams.all()]

    def getval_users(self, obj):
        return [x.id for x in obj.team_user.all()]


@DB
class TeamDQ(DataSQLQuery):
    model = Team
    data_model = TeamDB

    def query_bottom(self, qs, field, value, regex=False):
        if value:
            qs = qs.annotate(subteam_count=Count('subteams'))
            return qs.filter(subteam_count=0)
        return qs

@DB
class TrafficstatDQ(DataSQLQuery):
    model = TrafficStat


@DB
class StatDoctorDaily(DataSQLQuery):
    model = StatDoctorDaily
