# coding=utf-8
from django.conf import settings
from rpc.decorators import bind
from rpc.tool.dict_mixin import to_dict
from api.models.push_authorization import PushGiftRecord
from rpc.tool.error_code import gen, CODES


@bind('api/push_gift_record/get')
def get_push_gift_record(user_id):
    """
    获取用户 授权接收push领取礼包的记录
    :param user_id: 用户id
    :return:
    """
    try:
        push_gift_record = PushGiftRecord.objects.using(settings.SLAVE_DB_NAME).get(user_id=user_id)
    except:
        push_gift_record = None

    if push_gift_record:
        push_gift_record = to_dict(push_gift_record)

    return push_gift_record


@bind('api/push_gift_record/create')
def create_push_gift_record(user_id, gift_id):
    """
    创建用户 授权接收push领取礼包的记录
    :param user_id: 用户id
    :return:
    """
    try:
        record = PushGiftRecord.objects.get(user_id=user_id)
    except:
        record = None

    if record:
        gen(CODES.COUPON_YOU_HAVE_GOT_ONE)

    obj = PushGiftRecord.objects.create(
        user_id=user_id,
        gift_id=gift_id
    )

    return obj.id
