'''
This plugin attemps to create something similar to menuitems,
but more meaningful with respect to l10n
'''
from __future__ import print_function

from pelican import signals


def add_localmenuitems(generator):
    menu = {}  # lang: list of pages
    for page in generator.context['pages']:
        menu.setdefault(page.lang, [])
        for tr in page.translations:
            menu.setdefault(tr.lang, [])
    print('we have langs ' + ','.join(menu.keys()))
    for page in sorted(generator.context['pages'],
                       key=lambda x: int(x.navbar_sort)):
        defined_langs = []
        menu[page.lang].append(page)
        defined_langs.append(page.lang)
        for tr in page.translations:
            menu[tr.lang].append(tr)
            defined_langs.append(tr.lang)
        for lang in menu.keys():
            if lang not in defined_langs:
                menu[lang].append(page)

    menuitems = {}
    for lang in menu:
        menuitems[lang] = []
        for page in menu[lang]:
            menuitems[lang].append((page.title, page.url))

    generator.context['LOCALMENUITEMS'] = menuitems


def register():
    signals.page_generator_finalized.connect(add_localmenuitems)
