from oscar.core.loading import get_class, get_model

EventHandler = get_class("order.processing", "EventHandler")
PaymentEventType = get_model("order", "PaymentEventType")


def record_payment_events(
    order, order_status, payment_status, description, reference=None
):
    handler = EventHandler()
    handler.handle_order_status_change(order, order_status, description)
    create_payment_events(order, payment_status, reference)


def set_user_properties(user, **props):
    """
    Add properties to the user

    >>> user = AttributeError()
    >>> sameuser = set_user_properties(user, lol="nub", koe=1)
    >>> user.lol
    'nub'
    >>> user.koe
    1
    >>> sameuser.lol
    'nub'
    >>> sameuser.koe
    1
    """
    user.__dict__.update(props)
    return user


def create_payment_events(order, event_type, reference=None):
    """Create payment event for all lines"""
    event_type, __ = PaymentEventType.objects.get_or_create(name=event_type)
    handler = EventHandler()
    handler.create_payment_event(
        order,
        event_type,
        order.total_incl_tax,
        lines=order.lines.all(),
        line_quantities=[line.quantity for line in order.lines.all()],
        reference=reference if reference is not None else order.number,
    )


def create_or_record_payment_events(order, event_type, description, reference=None):
    if order.status == event_type:
        create_payment_events(order, event_type, reference)
    else:
        record_payment_events(
            order=order,
            order_status=event_type,
            payment_status=event_type,
            description=description,
            reference=reference,
        )
