# coding=utf-8
from api.models.order import RefundLock
from api.models.order import CashBackLock
from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES
from rpc.tool.log_tool import repeat_refund_logger
from pay.tool.types import REFUND_TYPE


def is_locked(order_id, refund_type):
    if refund_type == REFUND_TYPE.REFUND:
        Lock = RefundLock
    else:
        Lock = CashBackLock
    try:
        Lock.objects.get(order_id=order_id)
        repeat_refund_logger.error(
            "Order: {order_id} refund_type: {refund_type} (0 is refund, 1 is cashback)".format(order_id=order_id,
                                                                                               refund_type=refund_type))
        raise gen(CODES.ORDER_REFUDN_HAS_BEEN_OPERATED)

    except Lock.DoesNotExist:
        pass


def lock(order_id, refund_type):
    if refund_type == REFUND_TYPE.REFUND:
        Lock = RefundLock
    else:
        Lock = CashBackLock
    Lock.objects.create(order_id=order_id)