from .grpc.discount_pb2 import (
    BasketRequest,
    CouponRequest,
    InstallmentBasketRequest,
    TieredDiscountRequest,
    UsageRequest,
)
from .grpc.discount_pb2_grpc import DiscountControllerStub

SUCCESS_CODE = "0"


def _singletonize_class_vars(cls):
    for attr_name, attr_value in cls.__dict__.items():
        if isinstance(attr_value, type):  # it's a class
            orig_cls = attr_value

            class SingletonWrapper(orig_cls):
                _instances = {}

                def __new__(cls, *args, **kwargs):
                    if cls not in cls._instances:
                        cls._instances[cls] = super().__new__(cls)
                    return cls._instances[cls]

            setattr(cls, attr_name, SingletonWrapper)
    return cls


@_singletonize_class_vars
class Stubs:
    DISCOUNT = DiscountControllerStub


class RequestMessages:
    CALCULATE_BY_COUPON = CouponRequest
    CALCULATE_BY_BASKET = BasketRequest
    CALCULATE_INSTALLMENT_BY_BASKET = InstallmentBasketRequest
    CALCULATE_TIERED_DISCOUNT = TieredDiscountRequest
    CREATE_USAGE = UsageRequest


class RPCMethodNames:
    CALCULATE_BY_COUPON = "CalculateByCoupon"
    CALCULATE_BY_BASKET = "CalculateByBasket"
    CALCULATE_INSTALLMENT_BY_BASKET = "CalcInstallmentByBasket"
    CALCULATE_TIERED_DISCOUNT = "CalculateTieredDiscount"
    CREATE_USAGE = "CreateUsage"
