import json
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder
from gm_dataquery.dataquery import DataSQLQuery
from api.models import BusinessCityRelation, User
from gm_dataquery.db import DB

from themis.models import Team


class BusinessCityRelationDB(DataBuilder):
    def getval_city_ids(self, obj):
        return [item.split("'")[1] for item in obj.city_ids.split('[')[-1].split(']')[0].split(',')]

    def getval_user_name(self, obj):
        user = None
        if obj.username:
            user = User.objects.filter(id=obj.username).first()
        return user.username if user else ''

    def getval_advertisement_group(self, obj):
        group = []
        for g in obj.group.split('[')[-1].split(']')[0].split(','):
            team = Team.objects.filter(id=g.split("'")[1]).first()
            group.append(team.name if team else '')
        return group
    def getval_group(self, obj):
        return [item.split("'")[1] for item in obj.group.split('[')[-1].split(']')[0].split(',')]


@DB
class BusinessCityRelationDQ(DataSQLQuery):
    model = BusinessCityRelation
    data_model = BusinessCityRelationDB

    def filter_advertisement_name(self, srch_key, srch_val, regex):
        q = Q(advertisement_name=srch_val)
        return q

    def filter_group(self, srch_key, srch_val, regex):
        team = Team.objects.filter(name=srch_val).first()
        q = Q(group__contains=team.id if team else '')
        return q
