from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.mimas import FAKE_REPLY_BAND_TYPE

from communal.models.fake_reply import FakeReplyPool, FakeReplyConfig, FakeReplyConfigMapReply
from talos.services import TagV3Service
from talos.rpc import get_current_rpc_invoker


class ReplyPoolDB(DataBuilder):
    pass


@DB
class ReplyPoolDQ(DataSQLQuery):
    model = FakeReplyPool
    data_model = ReplyPoolDB


class FakeReplyConfigDB(DataBuilder):

    def getval_reply_count(self, obj):
        return FakeReplyConfigMapReply.objects.filter(config_id=obj.id).count()

    def getval_tag_name(self, obj):
        if obj.band_type == FAKE_REPLY_BAND_TYPE.TAG:
            tag = TagV3Service.get_tags_by_tag_v3_ids([int(obj.tag_id)])
            tag_v3_info = TagV3Service.format_tag_v3(tag.get(int(obj.tag_id)))
            return tag_v3_info['name']
        elif obj.band_type == FAKE_REPLY_BAND_TYPE.TAG_GROUP:
            result = get_current_rpc_invoker()[
                'api/tag_v3_category'](category_ids=[int(obj.tag_group_id)]).unwrap()
            category = result.get(str(obj.tag_group_id), {})
            return category.get('name', '')


@DB
class ReplyPoolDQ(DataSQLQuery):
    model = FakeReplyConfig
    data_model = FakeReplyConfigDB

    def filter_tag_id(self, srch_key, srch_val, regex=False):
        return Q(tag_id=int(srch_val), band_type=FAKE_REPLY_BAND_TYPE.TAG)

    def filter_tag_group_id(self, srch_key, srch_val, regex=False):
        return Q(tag_group_id=int(srch_val), band_type=FAKE_REPLY_BAND_TYPE.TAG_GROUP)

