from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
import os
import re
from django.utils.translation import get_language
from django.urls import URLPattern

"""
Django URL configuration for the cms application.

This module defines the URL patterns for the cms application,  by default including
routes for the home page, login, and logout.

Example:
    To add a new URL pattern, create a new instance of the `path` function
    and pass in the URL pattern, view function, file_directory_attr where you include the content index file for the page,
    and the db_table_attr where you include the database name for the table
    arguments. For example:

    -- path('admin/new-page/'', views.cms, {'file_directory_attr': 'new_page.json', 'db_table_attr': 'cms_page'}, name='new_page')

    This would create a new URL pattern for the `/cms/new-page/` URL,
    which would be handled by the `new_page_view` function in the `views`
    module.

Attributes:
    app_name (str): The name of the Django application.
    urlpatterns (list): A list of URL patterns for the application.
"""

app_name = "cms"

def cms_context_procces():
    # Initialize the list of names to return in the context
    cms_files = []

    # Check if 'cms' is in INSTALLED_APPS
    if 'cms' not in settings.INSTALLED_APPS:
        return {'cms_files': cms_files}  # Return an empty list if 'cms' is not installed

    # Define the directory where the files are stored
    cms_content_index_dir = os.path.join(settings.BASE_DIR, 'cms', "content_index", get_language())

    # Check if the directory exists
    if not os.path.exists(cms_content_index_dir):
        return {'cms_files': cms_files}

    # Regular expression to match files like {{name}}_content_index.json
    name_pattern = re.compile(r'^(?P<name>.+)_content_index\.json$')

    # List all files in the directory and extract names
    for file in os.listdir(cms_content_index_dir):
        match = name_pattern.match(file)
        if match:
            # Extract the name part from the filename
            cms_files.append(match.group('name'))

    # Return the list of names as part of the context
    return {'cms_files': cms_files}

def generate_dynamic_urls():
    cms_files = cms_context_procces()['cms_files']  # Get the list of CMS files
    
    # Initial URLS
    urlpatterns = []
    
    # Filter urls to remove duplicates and broken links
    seen_patterns = set()
    unique_urlpatterns = []

    # Create URL patterns for each CMS file
    for cms_file in cms_files:
        
        # Create page urls
        for languages in settings.LANGUAGES:
            
            for filtered_name in cms_files:
                
                if languages[0] == settings.DEFAULT_LANGUAGE:
                    
                    pattern = path(f'admin/{filtered_name}/', views.cms_page, {
                        'file_directory_attr': f'{cms_file}_content_index.json',
                        'db_table_attr': f'{cms_file}',
                        "page_name": f"Content - {cms_file.capitalize()}"
                    }, name=f"{str(filtered_name).capitalize()}")
                    
                    urlpatterns.append(pattern)
                    
                else:
                    pattern = path(f'admin/{languages[0]}/{filtered_name}/', views.cms_page, {
                        'file_directory_attr': f'{cms_file}_content_index.json',
                        'db_table_attr': f'{filtered_name}',
                        "page_name": f"Content - {cms_file.capitalize()}"
                    }, name=f"{str(filtered_name).capitalize()} - {str(languages[1]).capitalize()}")
                    
                    urlpatterns.append(pattern)
    
    # Create landing URLs
    for languages in settings.LANGUAGES:
        
        if settings.DEBUG:
            landing_file = 'home_content_index.json'
            landing_name = 'home'
            
        else:
            landing_file = 'home_content_index.json'
            landing_name = 'home'
            
        if languages[0] == settings.DEFAULT_LANGUAGE:
            pattern = path(f'admin/', views.cms_page, {
                'file_directory_attr': landing_file, 
                'db_table_attr': landing_name, 
                "page_name": "Admin"
            }, name='Admin Home')
            
            unique_urlpatterns.append(pattern)  
            
        else:
            pattern = path(f'admin/{languages[0]}/', views.cms_page, {
                'file_directory_attr': landing_file, 
                'db_table_attr': landing_name, 
                "page_name": "Admin"
            }, name='Admin Home')
            
            unique_urlpatterns.append(pattern)  
    
    for pattern in urlpatterns:
        # Check if the item is a URL pattern
        if isinstance(pattern, URLPattern) and not str(pattern.pattern).endswith("None/"):
            
            pattern_str = str(pattern.pattern)
            if pattern_str not in seen_patterns:
                
                args = pattern.default_args.get('file_directory_attr')
                file_pattern = re.compile(r'^(?P<name>.+)_content_index\.json$')
                file_name = file_pattern.match(args).group(1)
                url_name = re.search(r'[^/]+(?=/$|$)', pattern_str)
                
                if url_name:
                    # Add the URL to the list of unique URLs if its the proper url with proper data
                    if str(url_name.group()) == file_name:
                        seen_patterns.add(pattern_str)
                        unique_urlpatterns.append(pattern)             
    
    return unique_urlpatterns

urlpatterns = [    
    path("admin/cms/demo/", views.demo),
    
    path('cms/upload/', views.upload_file, name='upload_file'),
    
    path('cms/media/<path:path>/', views.serve_media, {'app_name': 'cms'}), 
]

from django.conf.urls.i18n import i18n_patterns

urlpatterns += generate_dynamic_urls()

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)