import logging

from oscar.core.loading import get_class, get_model

from ocyan.plugin.oscar.info import OSCAR_NEEDS_OXYAN

logger = logging.getLogger(__name__)

if OSCAR_NEEDS_OXYAN:
    CommunicationEventType = get_model("communication", "CommunicationEventType")
else:
    CommunicationEventType = get_model("customer", "CommunicationEventType")

BccDispatcher = get_class("customer.utils", "BccDispatcher")


def send_message(ctx, code, bcc_admins=False, **kwargs):
    try:
        event_type = CommunicationEventType.objects.get(code=code)
    except CommunicationEventType.DoesNotExist:
        event_type = None

    if ctx.order.communication_events.filter(event_type=event_type).exists():
        logger.info("Not sending message for event %s, message has allready been sent.")
        return

    messages = CommunicationEventType.objects.get_and_render(code, ctx)

    if "attachments" in kwargs:
        messages["attachments"] = kwargs["attachments"]

    if messages and messages["body"]:
        logger.info("Order #%s - sending %s messages", ctx.order.number, code)
        dispatcher = BccDispatcher(bcc_admins, logger)
        dispatcher.dispatch_order_messages(ctx.order, messages, event_type, **kwargs)
    else:
        logger.warning(
            "Order #%s - no %s communication event type", ctx.order.number, code
        )
