# -*- coding:utf-8 -*-
'''
美购操作
owner: wangkai
'''

import traceback

from gm_types.error import ERROR as ERROR_CODES

from rpc.tool.error_code import gen
from rpc.tool.log_tool import goods_logger

from api.models import Service, ServiceItem

def validate_positive_num(num_key):
    '''判断参数为非负整数'''
    if not num_key or not str(num_key).isdigit():
        return False
    return True

def get_spu_obj_by_id(spu_id, raisable=True):
    '''
    根据美购id获取美购对象
    param raisable: 是否抛出异常
    '''
    if not validate_positive_num(spu_id):
        return None
    try:
        return Service.objects.get(id=int(spu_id))
    except:
        goods_logger.error('[GOODS]{ERROR} get service(%s) failed for reason:\n%s' % (spu_id, traceback.format_exc()))
        if raisable:
            gen(ERROR_CODES.SERVICE_NOT_EXSIT)
    return None


def get_sku_obj_by_id(sku_id, raisable=True):
    '''
    根据sku_id获取sku对象
    '''
    if not validate_positive_num(sku_id):
        return None

    try:
        return ServiceItem.objects.get(id=int(sku_id))
    except:
        goods_logger.error('[GOODS]{ERROR} get sku(%s) failed for reason: \n%s' % (sku_id, traceback.format_exc()))
        if raisable:
            gen(ERROR_CODES.SKU_NOT_FOUND)
    return None

