from cms.functions import *
from admin_base.functions import SpinnerWithMessage
from django.core.management.base import BaseCommand
from django.conf import settings
import os
from termcolor import colored

class Command(BaseCommand):
    help = 'Check form fields and update database'

    def add_arguments(self, parser):
        parser.add_argument(
            "remove", nargs='?', default=None, help="Remove all CMS info from website"
        )

    def handle(self, *args, **options):
        
        remove = bool(options["remove"])
        
        spinner = SpinnerWithMessage("Connecting {} app with {} app".format(colored("CMS", 'blue'), colored("Website", 'blue')))
        
        spinner.start()
        
        content_index_path = os.path.join(settings.BASE_DIR, 'cms', 'content_index')
        
        pages = []
        
        if os.path.exists(content_index_path):
            
            for lang_folder in os.listdir(content_index_path):
                for content_index_file in os.listdir(os.path.join(content_index_path, lang_folder)):
                    table_name = re.match(r"(\w+)_content_index\.json", content_index_file)
                    if table_name:
                        spinner.update(f"Connecting {table_name.group(1)} page with CMS")
                        connect_page = check_form_fields(table_name.group(1), lang_folder, remove)
        
        if connect_page == 'remove':
            spinner.stop("Succesfully removed CMS app", 'success')
             
        else:
            spinner.stop("Succesfully connected CMS app", 'success')
