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

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.error import ERROR
from django.db import transaction

from api.models import DiarySpreadFit
from api.models.area import City
from rpc.exceptions import GaiaRPCFaultException



@DB
class DiarySpreadFitDQ(DataSQLQuery):
    model = DiarySpreadFit

    def create(self, **kwargs):
        city = kwargs.pop('city')
        has_city = DiarySpreadFit.objects.filter(city=city[0]).exists()
        if has_city:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'不能重复添加城市', data=None)
        city_obj = City.objects.get(id=city[0])
        kwargs['city'] = city_obj
        obj = DiarySpreadFit.objects.get_or_create(**kwargs)
        return {'id': obj[0].id}

    def update(self, updates, **kwargs):
        city = updates.pop('city')
        city_obj = City.objects.get(id=city[0])
        updates['city'] = city_obj
        with transaction.atomic(self.model.objects.db):
            for obj in self.model.objects.select_for_update().filter(**kwargs):
                for k, v in updates.items():
                    setattr(obj, k, v)
                obj.save()





