# coding=utf-8
from rpc.decorators import bind_context
from api.models import RecommendUserAttention
from django.db import IntegrityError, transaction
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.log_tool import info_logger
from rpc.tool.dict_mixin import to_dict
from rpc.cache import req_data_cache
from hera.actions.order import OrderAction
import json


uri_pre = 'hera/recommanduserattention'


def save_all(recommanduserattention_id, recommanduserattention_info):
    if not recommanduserattention_id:
        try:
            recommanduserattention = RecommendUserAttention.objects.create(**recommanduserattention_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            recommanduserattention = RecommendUserAttention.objects.get(id=recommanduserattention_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException

        for k, v in recommanduserattention_info.iteritems():
            setattr(recommanduserattention, k, v)
        recommanduserattention.save()


@bind_context(uri_pre + '/edit')
@transaction.atomic
def recommanduserattention_edit(ctx, recommanduserattention_info=None, urls=None):
    if recommanduserattention_info is None:
        return None
    for instance in recommanduserattention_info:
        save_all(instance.pop('id'), instance)

    return 1


@bind_context(uri_pre + '/get')
def recommanduserattention_get(ctx):
    """
    获取所有推荐项目
    """
    try:
        recommanduserattentions = RecommendUserAttention.objects.filter(is_delete=False)
    except IntegrityError:
        raise RPCIntegrityError
    recommanduserattention_data = map(lambda x: to_dict(x), recommanduserattentions)
    return recommanduserattention_data


@bind_context(uri_pre + '/delete')
@transaction.atomic
def recommanduserattention_delete(ctx, recommanduserattention_id):
    """
    删除相关推荐项目根据id
    """
    if recommanduserattention_id is None:
        return None
    try:
        recommanduserattention = RecommendUserAttention.objects.get(id=recommanduserattention_id)
    except IntegrityError:
        raise RPCIntegrityError
    recommanduserattention.is_delete = True
    recommanduserattention.save()
    return recommanduserattention_id
