import unittest

from bs4 import BeautifulSoup
from django.test import TestCase

from ocyan.core.fender import config

from ocyan.plugin.wagtail_oscar_integration.constants import (
    INCLUDE_CHILD_PRODUCTS_IN_SITEMAP,
)

LANGUAGE_CODE = config.get("django", "language_code", "en")


class SiteMapSmokeTest(TestCase):
    fixtures = [
        "wagtail_oscar_integration/catalogue",
        "wagtail_oscar_integration/sites",
        "wagtail_oscar_integration/pages",
    ]

    @unittest.skipIf(INCLUDE_CHILD_PRODUCTS_IN_SITEMAP, "Children in sitemap")
    def test_product_sitemap_browsable(self):
        response = self.client.get("/sitemap-products.xml?zult-hdk")
        soup = BeautifulSoup(response.content.decode())

        num_expected_urls = 5
        if config.i18n_enabled:
            num_expected_urls = num_expected_urls * len(
                config.get("i18n", "languages", [LANGUAGE_CODE])
            )

        self.assertEqual(len(soup.find_all("url")), num_expected_urls)
        urls = soup.find_all("loc")
        self.assertEqual(
            len(urls), len(set(urls)), "There should be no duplicates in the sitemap"
        )

    @unittest.skipUnless(INCLUDE_CHILD_PRODUCTS_IN_SITEMAP, "No children in sitemap")
    def test_product_sitemap_browsable_children(self):
        response = self.client.get("/sitemap-products.xml?lalalalal")
        soup = BeautifulSoup(response.content.decode())

        num_expected_urls = 7
        if config.i18n_enabled:
            num_expected_urls = num_expected_urls * len(
                config.get("i18n", "languages", [LANGUAGE_CODE])
            )

        self.assertEqual(len(soup.find_all("url")), num_expected_urls)
        urls = soup.find_all("loc")
        self.assertEqual(
            len(urls), len(set(urls)), "There should be no duplicates in the sitemap"
        )

    def test_category_sitemap(self):
        response = self.client.get("/sitemap-categories.xml")
        soup = BeautifulSoup(response.content.decode())

        num_expected_urls = 2
        if config.i18n_enabled:
            num_expected_urls = num_expected_urls * len(
                config.get("i18n", "languages", [LANGUAGE_CODE])
            )

        self.assertEqual(len(soup.find_all("url")), num_expected_urls)
        urls = soup.find_all("loc")
        self.assertEqual(
            len(urls), len(set(urls)), "There should be no duplicates in the sitemap"
        )

    def test_page_sitemap(self):
        response = self.client.get("/sitemap-pages.xml")
        soup = BeautifulSoup(response.content.decode())

        self.assertEqual(len(soup.find_all("url")), 1)
        urls = soup.find_all("loc")
        self.assertEqual(
            len(urls), len(set(urls)), "There should be no duplicates in the sitemap"
        )
