from django.conf import settings
from django.utils.translation import override

from wagtail.contrib.sitemaps import sitemap_generator


class WagtailSitemap(sitemap_generator.Sitemap):
    i18n = getattr(settings, "WAGTAIL_I18N_ENABLED", False)
    languages = getattr(settings, "WAGTAIL_CONTENT_LANGUAGES", None)
    latest_lastmod = None

    def _urls(self, page, protocol, domain):
        if not self.i18n:
            return super()._urls(page, protocol, domain)

        urls = []
        last_mods = set()

        for item, code in self.paginator.page(page).object_list:
            # activate the langyage passed by the i18n iterator
            with override(code[0]):
                # get the localised version of the page
                i18n_item = item.specific.localized

                # if there is no localized version, skip the page.
                if i18n_item.locale.language_code != code[0]:
                    continue

                url_info_items = i18n_item.get_sitemap_urls(self.request)

                for url_info in url_info_items:
                    urls.append(url_info)
                    last_mods.add(url_info.get("lastmod"))

        # last_mods might be empty if the whole site is private
        if last_mods and None not in last_mods:
            self.latest_lastmod = max(last_mods)
        return urls


sitemaps = {
    "pages": WagtailSitemap,
}
