import logging

from django.conf import settings
from django.http import Http404
from importlib import import_module

from haso_payment.exceptions import PaymentFlowException
from haso_payment.helpers import get_deps

module, _class = settings.PZ_SERVICE_CLASS.rsplit(".", 1)
Service = getattr(import_module(module), _class)

logger = logging.getLogger(__name__)


class CheckoutService(Service):

    def get_form_data(self, request):
        return self._get_form_data(request)

    def _retrieve_pre_order(self, request):
        path = "/orders/checkout/?page=OrderNotePage"
        response = self.get(
            path,
            request=request,
            headers={
                "X-Requested-With": "XMLHttpRequest"
            }
        )
        return self.normalize_response(response)

    def _get_form_data(self, request):
        response = self._retrieve_pre_order(request)

        pre_order = response.data.get("pre_order", {})
        payment_option = pre_order.get("payment_option", {})
        payment_option_slug = payment_option.get("slug", "")

        if not payment_option_slug:
            raise Http404("Payment option not found in pre-order data.")

        session_id = request.GET.get("sessionId")
        salt, hash, extension_url = get_deps(
            session_id=session_id,
            payment_option_slug=payment_option_slug,
        )

        address = pre_order.get("shipping_address") or {}

        if not address:
            raise PaymentFlowException(
                "Shipping address not found in pre-order data.",
            )

        body = {
            "hash": hash,
            "salt": salt,
            "shipping_address": self._get_shipping_address(address)
        }
        return extension_url, body

    def _get_shipping_address(self, address_response):
        if not address_response:
            return {}

        return {
            "first_name": address_response.get("first_name"),
            "last_name": address_response.get("last_name"),
            "phone_number": address_response.get("phone_number"),
            "line": address_response.get("line"),
            "district": address_response["district"]["name"],
            "township": address_response["township"]["name"],
            "city": address_response["city"]["name"],
            "country": address_response["country"]["code"].upper(),
            "zip_code": address_response["postcode"],
        }
