from users.models import User
from .models.module import Module, ModuleLevel, ModuleCategory

def analyze_module_meta_titles():
    all_nodes = []

    for module in Module.objects.all():
        print(f"{module.get_parent() }         {module.meta_title} :  {module.title}")

        nodes = [i.strip() for i in [module.get_parent().title] + module.meta_title.split(' – ')]
        all_nodes.append(nodes)

    print("")

    for i in range(3):
        leafs = [node[i] for node in all_nodes if len(node) > i+1]
        leafs.sort()
        print(f"{i}.: {set(leafs)}")


def create_default_levels_and_categories():
    ModuleLevel.objects.get_or_create(name=f"Alle Lehrjahre", filter_attribute_type="all", order=0)

    for lehrjahr in range(1,4):
        module_category, created = ModuleLevel.objects.get_or_create(name=f"{lehrjahr}. Lehrjahr", order=lehrjahr)


    ModuleCategory.objects.get_or_create(name=f"Alle Lernfelder", filter_attribute_type="all", order=0)

    for category in range(1, 5):
        ModuleCategory.objects.get_or_create(name=f"Lernfeld {category}", order=category)


def categorize_modules():
    for level in ModuleLevel.objects.all():
        modules = Module.objects.filter(level__isnull=True, meta_title__icontains=level.name)
        print(f"{level.name}: {modules.count()}")
        modules.update(level=level)

    for category in ModuleCategory.objects.all():
        modules = Module.objects.filter(category__isnull=True, meta_title__contains=category.name)
        print(f"{category.name}: {modules.count()}")
        modules.update(category=category)


def uncategorize_modules():
    User.objects.all().update(last_module_level=None)
    #
    ModuleCategory.objects.all().delete()
    ModuleLevel.objects.all().delete()

def delete_unused_levels():
    for level in ModuleLevel.objects.filter(filter_attribute_type="exact"):
        if not level.module_set.exists():
            level.delete()

def delete_unused_categories():
    for category in ModuleCategory.objects.filter(filter_attribute_type="exact"):
        if not category.module_set.exists():
            category.delete()
