from django.shortcuts import redirect
from django.utils.translation import override
from django.views.generic.base import TemplateView

from oscar.core.loading import get_model

from ocyan.core.fender import config
from ocyan.plugin.oscar.pipeline import (
    PIPELINE_STATUS_CANCELLED,
    PIPELINE_STATUS_PAID,
    PIPELINE_STATUS_PENDING_PAYMENT,
)
from ocyan.plugin.oscar.utils import create_payment_events, record_payment_events

from .constants import PAYMENT_KEY

Order = get_model("order", "Order")
Source = get_model("payment", "Source")
SourceType = get_model("payment", "SourceType")


class DummyPaymentView(TemplateView):
    template_name = "payment/dummy/payment.html"

    def get_context_data(self, **kwargs):
        return {"help_text": config.get("ocyan_dummy_payment_plugin", "help_text", "")}

    def get(self, request, *args, **kwargs):
        order = Order._default_manager.get(  # pylint: disable=W0212
            pk=self.request.session["checkout_order_id"]
        )
        if order.status != PIPELINE_STATUS_PENDING_PAYMENT:
            record_payment_events(
                order,
                PIPELINE_STATUS_PENDING_PAYMENT,
                PIPELINE_STATUS_PENDING_PAYMENT,
                "Pending payment from dummy payment",
            )
        else:
            create_payment_events(order, PIPELINE_STATUS_PENDING_PAYMENT)

        return super().get(request, *args, **kwargs)

    def post(self, request):
        reference = "dummy payment reference"
        order = Order._default_manager.get(  # pylint: disable=W0212
            pk=self.request.session["checkout_order_id"]
        )
        if request.POST.get("_try-again"):
            create_payment_events(order, PIPELINE_STATUS_CANCELLED)
            return redirect("checkout:try-again")

        source_type = SourceType.objects.get(code=PAYMENT_KEY)
        source, _ = Source.objects.get_or_create(
            order=order,
            source_type=source_type,
            reference=reference,
            defaults={"amount_allocated": order.total_incl_tax},
        )

        # declare source to be paid in full immediately
        source.debit(reference=reference, status=PIPELINE_STATUS_PAID)

        record_payment_events(
            order, PIPELINE_STATUS_PAID, PIPELINE_STATUS_PAID, "Paid with dummy payment"
        )

        with override(order.language_code):
            return redirect("checkout:thank-you")
