# coding=utf-8

from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict
from gm_dataquery.client import Model
from gm_rpcd.all import RPCDFaultException
from gm_types.error import ERROR


from ..models import CityWhiteList


class CityWhiteListDB(DataBuilder):

    def getval_name(self, obj):
        data_model = Model('gaia', 'city', ['id', 'name'])
        name = data_model.get(id=obj.city_id)['name']
        return name


@DB
class CityWhiteListDQ(DataSQLQuery):
    model = CityWhiteList
    data_model = CityWhiteListDB

    @classmethod
    def create(self, **kwargs):
        try:
            obj = self.model.objects.create(**kwargs)
        except:
            raise RPCDFaultException(ERROR.UNIVERSAL, '该城市已在白名单中')
        return to_dict(obj)

    @classmethod
    def update(self, updates, **kwargs):
        obj = self.model.objects.get(id=kwargs['id']).delete()
        return kwargs
