from django.conf import settings
from django.contrib.sitemaps import Sitemap
from django.contrib.sites.models import Site

from verify_trusted.companies.models import Company
from django.contrib.sitemaps.views import index
from django.http import HttpResponse


if settings.DJANGO_SITEMAP_LIMIT is None:
    limit = 20000 if settings.IS_PRODUCTION else 10
else:
    limit = settings.DJANGO_SITEMAP_LIMIT

def custom_index(request, sitemaps,
          template_name='sitemap_index.xml', content_type='application/xml',
          sitemap_url_name='django.contrib.sitemaps.views.sitemap'):
    
    content = index(request, sitemaps,
          template_name, content_type,
          sitemap_url_name)
    response_content = content.render().content.decode('utf-8')
    response_content = response_content.replace('<link type="text/css" rel="stylesheet" id="dark-mode-custom-link"/>', '')
    response_content = response_content.replace('<link type="text/css" rel="stylesheet" id="dark-mode-general-link"/>', '')
    response_content = response_content.replace('<style lang="en" type="text/css" id="dark-mode-custom-style"/>', '')
    response_content = response_content.replace('<style lang="en" type="text/css" id="dark-mode-native-style"/>', '')
    response_content = response_content.replace('<style lang="en" type="text/css" id="dark-mode-native-sheet"/>', '')
    content = HttpResponse(response_content, content_type=content_type)
    return content


class CompanySiteMap(Sitemap):
    changefreq = 'monthly'
    priority = 0.8
    protocol = 'https'
    limit = limit

    def get_urls(self, page=1, site=None, protocol=None):
        sitemap_site = settings.DJANGO_SITEMAP_SITE
        if sitemap_site is not None:
            site = Site(domain=sitemap_site, name=sitemap_site)
        return super().get_urls(page, site, protocol)

    def items(self):
        return Company.objects.only('id', 'url', 'modified').all().order_by('-pk')

    def lastmod(self, obj: Company):
        return obj.modified

    def location(self, obj: Company):
        return '/reviews/%s' % obj.url
