# coding:utf-8

import json
from functools import partial

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

from launch.models import (
    RecommendCard,
    FollowQuestionGroup,
    AIQuestion,
    Theme,
)


class RecommendCardDB(DataBuilder):
    pass


@DB
class RecommendCardDQ(DataSQLQuery):
    model = RecommendCard
    data_model = RecommendCardDB


class AIQuestionGroupDB(DataBuilder):

    def getval_length(self, obj):

        try:
            length = len(json.loads(obj.content))
        except:
            length = 0

        return length


def add_relation_question():

    def getval_image(self, obj, i=1):
        try:
            return obj.contents[i-1]["image_url"]
        except:
            return None

    def getval_question_id(self, obj, i=1):

        try:
            return obj.contents[i-1]["question_id"]
        except:
            return None

    def f(callable, i):
        def wrap(*args, **kwargs):
            wrap_func = partial(callable, i=i)
            return wrap_func(*args, **kwargs)
        return wrap

    for i in range(1, 20):
        setattr(AIQuestionGroupDB, "getval_question_img_" + str(i), f(getval_image, i=i))
        setattr(AIQuestionGroupDB, "getval_question_" + str(i), f(getval_question_id, i=i))


add_relation_question()


@DB
class AIQuestionGroupDQ(DataSQLQuery):
    model = FollowQuestionGroup
    data_model = AIQuestionGroupDB


class AIQuestionDB(DataBuilder):
    pass


@DB
class AIQuestionDQ(DataSQLQuery):
    model = AIQuestion
    data_model = AIQuestionDB


class AIThemeDB(DataBuilder):
    pass


@DB
class AIhemeDQ(DataSQLQuery):
    model = Theme
    data_model = AIThemeDB
