from django.conf import settings
from django.db import connection
from django.utils.translation import override
from uwsgidecoratorsfallback import spool

from oscar.core.loading import get_class, get_model

from ocyan.core.fender import config
from ocyan.main.loading import get_ocyan_class

get_offline_request = get_ocyan_class("wagtail_utils.utils", "get_offline_request")
send_message = get_class("order.shortcuts", "send_message")
OrderContext = get_class("order.context", "OrderContext")

try:
    InvoiceCreator = get_class("oscar_invoices.utils", "InvoiceCreator")
except LookupError:
    pass

Order = get_model("order", "Order")
PaymentMethod = get_model("checkout", "PaymentMethod")


@spool
def send_order_confirmation_message_async(args):
    # the spooler is forked so the db connection might be closed
    try:
        if not connection.is_usable():
            connection.close()
    except AttributeError:
        connection.close_if_unusable_or_obsolete()

    event_type = args["event_type"]
    order_id = args["order_id"]
    order = Order.objects.get(pk=order_id)
    request = get_offline_request(order.site.domain)

    with override(order.language_code):
        kwargs = {}
        if config.get("oscar_communications", "invoice", False):
            send_invoice = True
            if order.payment_source_type is not None:
                payment_method = PaymentMethod.objects.filter(
                    key=order.payment_source_type.code
                ).first()
                if payment_method is not None:
                    send_invoice = payment_method.send_invoice

            if send_invoice:
                ic = InvoiceCreator(request=request)
                invoice = ic.get_or_create_invoice(order)
                if invoice is not None:
                    kwargs["attachments"] = [invoice.document]

        ctx = OrderContext(order)
        send_message(ctx, event_type, bcc_admins=True, **kwargs)


@spool
def send_new_order_status_message_async(args):
    try:
        if not connection.is_usable():
            connection.close()
    except AttributeError:
        connection.close_if_unusable_or_obsolete()

    event_type = args["event_type"]
    order_id = args["order_id"]
    order = Order.objects.get(pk=order_id)
    order_status = "ORDER_STATUS_%s" % order.status.upper()
    bcc_admins = getattr(settings, "%s_BCC_ADMINS" % order_status, False)
    attach_invoice = getattr(settings, "%s_ATTACH_INVOICE" % order_status, False)

    with override(order.language_code):
        kwargs = {}

        if attach_invoice:
            request = get_offline_request(order.site.domain)
            ic = InvoiceCreator(request=request)
            invoice = ic.get_or_create_invoice(order)
            if invoice is not None:
                kwargs["attachments"] = [invoice.document]

        ctx = OrderContext(order)
        send_message(ctx, event_type, bcc_admins=bcc_admins, **kwargs)
