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

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.error import ERROR
from gm_types.gaia import SLIDE_USER_TYPE
from api.models import IndexFeed
from rpc.exceptions import GaiaRPCFaultException


class IndexFeedDB(DataBuilder):
    pass


@DB
class IndexFeedDQ(DataSQLQuery):
    model = IndexFeed
    data_model = IndexFeedDB

    def create(self, **kwargs):
        if kwargs.get('user_type') == SLIDE_USER_TYPE.ALL_USER:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='请不要选择全部用户类型', data=None)
        try:
            obj = IndexFeed.objects.create(**kwargs)
        except:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='存在用户类型, loading, 排序三者相同的数据', data=None)
        return {'id': obj.id}

    def update(self, updates, **kwargs):
        if updates.get('user_type') == SLIDE_USER_TYPE.ALL_USER:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='请不要选择全部用户类型', data=None)
        try:
            IndexFeed.objects.update_or_create(id=kwargs['id'], defaults=updates)
        except:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='存在用户类型, loading, 排序三者相同的数据', data=None)
        return super(IndexFeedDQ.sqlquery, self).update(updates, **kwargs)