import os

from apps.core.djacore_sitemap import index, sitemap
from apps.core.sitemap import DynamicSitemap, IndexSitemapGenerator
from apps.core.views.robots import robots_txt
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.static import serve

if settings.ADMIN_DIR == 'admin/':
    urlpatterns = [
        path(
            'admin/',
            admin.site.urls,
        ),
    ]
else:
    urlpatterns = [
        path(
            settings.ADMIN_DIR,
            admin.site.urls,
        ),
    ]

urlpatterns += [
    path('robots.txt', robots_txt, name='robots_txt'),
    path('ckeditor5/', include('django_ckeditor_5.urls')),
    path('upload/', include('django_ckeditor_5.urls')),  # CK5图片上传路径
    path('captcha/', include('captcha.urls')),  #验证码
]
# 媒体路径
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# 创建实例，但此时不会立即调用 get_solo()
dynamic_sitemap = DynamicSitemap()

# 重构条件逻辑，通过函数调用来获取 sitemap_obj
def get_sitemap_patterns():
    # 当有请求匹配到sitemap相关URL时，才会执行这里的代码并访问 .sitemap_obj 属性
    obj = dynamic_sitemap.sitemap_obj
    
    if isinstance(obj, IndexSitemapGenerator):
        return [
            path('sitemap.xml',
                 index, {
                     'sitemaps': obj.sitemaps,
                     'sitemap_url_name': 'section-sitemap'
                 },
                 name='sitemap-index'),
            path('sitemap-<section>.xml',
                 sitemap, {'sitemaps': obj.sitemaps},
                 name='section-sitemap'),
        ]
    else:
        return [
            path('sitemap.xml',
                 sitemap, {'sitemaps': {'all': obj}},
                 name='sitemap-monolithic'),
            path('sitemap_<int:page>.xml',
                 sitemap, {'sitemaps': {'all': obj}},
                 name='sitemap-monolithic'),
        ]

# 将生成的URL模式加入urlpatterns
urlpatterns += get_sitemap_patterns()

# 定义错误跳转页面

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path(r"__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.STATIC_URL,
                      document_root=os.path.join(settings.BASE_DIR,
                                                 'templates/themes'))

if not settings.DEBUG:

    urlpatterns += [
        re_path(r'^media/(?P<path>.*)$', serve,
                {'document_root': settings.MEDIA_ROOT}),
        re_path(r'^static/(?P<path>.*)$', serve,
                {'document_root': settings.STATIC_ROOT})
    ]
