# Path: gitcms/menus/models.py
# class Menu(models.Model):
#     name = models.CharField(tr('Name'), max_length=255)
#     fake_root = models.ForeignKey(MenuItem)
#     def _get_children(self):
#         return self.fake_root.children.all()
#     children = property(_get_children)
# 
# class MenuItem(models.Model):
#     name = models.CharField(tr('Name'), max_length=255)
#     title = models.CharField(tr('Title'), max_length=255, null=True)
#     url = models.CharField(tr('url'), max_length=255)
#     parent = models.ForeignKey('self', related_name='children', null=True)


from .models import Menu, MenuItem
from os import path
import os
import yaml

def loaddir(directory, clear=False):
    if clear:
        MenuItem.objects.all().delete()
        Menu.objects.all().delete()
    def _parse_children(parent, parent_obj):
        if 'children' not in parent:
            return
        for ch in parent['children']:
            child = MenuItem(name=ch['name'], url=ch['url'], title=ch.get('title', None), parent=parent_obj)
            child.save()
            _parse_children(ch, child)
    for menufile in os.listdir(directory):
        if menufile[0] == '.': continue
        for menu in yaml.load_all(open(path.join(directory,menufile))):
            fake_root = MenuItem(name='<fake-root>', url='fake-root-you-shouldnt-be-seeing-this-bro')
            fake_root.save()

# Path: gitcms/menus/models.py
# class Menu(models.Model):
#     name = models.CharField(tr('Name'), max_length=255)
#     fake_root = models.ForeignKey(MenuItem)
#     def _get_children(self):
#         return self.fake_root.children.all()
#     children = property(_get_children)
# 
# class MenuItem(models.Model):
#     name = models.CharField(tr('Name'), max_length=255)
#     title = models.CharField(tr('Title'), max_length=255, null=True)
#     url = models.CharField(tr('url'), max_length=255)
#     parent = models.ForeignKey('self', related_name='children', null=True)


# Path: gitcms/menus/load.py
from .models import Menu, MenuItem
from os import path
import os
import yaml


def loaddir(directory, clear=False):
    if clear:
        MenuItem.objects.all().delete()
        Menu.objects.all().delete()
    def _parse_children(parent, parent_obj):
        if 'children' not in parent:
            return
        for ch in parent['children']:
            child = MenuItem(name=ch['name'], url=ch['url'], title=ch.get('title', None), parent=parent_obj)
            child.save()
            _parse_children(ch, child)
    for menufile in os.listdir(directory):
        if menufile[0] == '.': continue
        for menu in yaml.load_all(open(path.join(directory,menufile))):
            fake_root = MenuItem(name='<fake-root>', url='fake-root-you-shouldnt-be-seeing-this-bro')
            fake_root.save()

            menu_obj = Menu(name=menu['name'], fake_root=fake_root)