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

from gm_dataquery.dataquery import DataSQLQuery, DataBuilder
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict

from wiki.models.collect import (
    Collect,
    CollectItem,
    CollectTagV3,
)
from wiki.logices.common_query import (
    NewWikiRelationWords,
    wiki_data_create,
    wiki_data_update,
)


class CollectDB(DataBuilder, NewWikiRelationWords):
    def getval_tags(self, obj):
        return list(obj.tags.values_list('tag_id', flat=True))

    def getval_tag_v3_ids(self, obj):
        return list(CollectTagV3.objects.filter(collect_id=obj.id).values_list("tag_v3_id", flat=True))

@DB
class CollectDQ(DataSQLQuery):
    model = Collect
    data_model = CollectDB

    def create(self, **kwargs):

        collect_obj = wiki_data_create(
            own_model=self.model,
            relation_models={
                "tag_v3": CollectTagV3,
            },
            model_param="collect_id",
            **kwargs
        )
        return to_dict(collect_obj)

    def update(self, updates, **kwargs):
        _collect_id = kwargs.get("id", 0)

        updates = wiki_data_update(
            _update_id=_collect_id,
            relation_models={
                "tag_v3": CollectTagV3,
            },
            updates=updates,
            model_param="collect_id"
        )

        return super(CollectDQ.sqlquery, self).update(updates, **kwargs)


@DB
class CollectItemDQ(DataSQLQuery):
    model = CollectItem
