import lxml.etree
import lxml.html

from ocyan.main.loading import get_ocyan_classes

# pylint: disable=unbalanced-tuple-unpacking
(
    transform_buttons,
    transform_menu_items,
    transform_listings,
    transform_icons,
    transform_forms,
    transform_pagination,
) = get_ocyan_classes(
    "wagtail_oscar_integration.transform",
    [
        "transform_buttons",
        "transform_menu_items",
        "transform_listings",
        "transform_icons",
        "transform_forms",
        "transform_pagination",
    ],
)


def transform_oscar_response(response):
    tree = lxml.html.fromstring(response.content)

    transform_buttons(tree)
    transform_menu_items(tree)
    transform_listings(tree)
    transform_icons(tree)
    transform_forms(tree)
    transform_pagination(tree)

    # Back to html, add doctype first as lxml removes this for some reason.
    response.content = "<!DOCTYPE html>\n%s" % lxml.html.tostring(
        tree, encoding="unicode"
    )

    return response


def oscar_dashboard_2_wagtail(get_response):
    def middleware(request):
        response = get_response(request)

        try:
            if "dashboard" in request.resolver_match.namespaces:
                if not response.status_code == 200:
                    return response

                if not response["Content-Type"].startswith("text/html"):
                    return response

                if not request.user.is_authenticated:
                    return response

                return transform_oscar_response(response)
        except AttributeError:
            pass

        return response

    return middleware
