from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.shortcuts import redirect
from django.utils.translation import get_language


class I18nPageMixin:
    def get_translations_and_self(self):
        return self.get_translations(inclusive=True).live()

    def route(self, request, path_components):
        use_wagtail_i18n = getattr(settings, "WAGTAIL_I18N_ENABLED", False)
        if use_wagtail_i18n and path_components:
            # request is for a child of this page
            child_slug = path_components[0]
            remaining_components = path_components[1:]

            try:
                subpage = self.get_children().get(slug=child_slug)
                return subpage.specific.route(request, remaining_components)
            except ObjectDoesNotExist:
                pass

            # see if a translation can route the url
            for translation in self.get_translations():
                try:
                    subpage = translation.get_children().get(slug=child_slug)
                    return subpage.specific.route(request, remaining_components)
                except ObjectDoesNotExist:
                    pass

            # the url could not be routed in any language
            raise Http404

        return super().route(request, path_components)

    def serve(self, request, *args, **kwargs):
        use_wagtail_i18n = getattr(settings, "WAGTAIL_I18N_ENABLED", False)
        if use_wagtail_i18n:
            active_language = get_language()
            # if the router returned a page in a different locale, redirect to
            # the correct url
            if active_language != self.locale.language_code:
                try:
                    translation = self.get_translations().get(
                        locale__language_code=active_language
                    )
                    return redirect(translation.get_url(request))
                except self.DoesNotExist:
                    pass

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

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