# Copyright (C) 2020 The Meme Factory, Inc.  http://www.karlpinc.com/

# This file is part of PGWUI_Menu.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#

# Karl O. Pinc <kop@karlpinc.com>
#
# Bugs:

from pyramid.view import view_config

from pgwui_common.view import base_view
from pgwui_common import plugin


def build_menu(request, pgwui, menu_items, component):
    '''Add a menu to menu_items, if there's a route'''
    conf = pgwui.get(component)
    if conf:
        try:
            route = request.route_url(component)
        except KeyError:
            pass
        else:
            menu_items.append((component, route, conf))


def build_menu_items(request, components):
    # Don't put the menu on the menu
    components.remove('pgwui_menu')

    pgwui = request.registry.settings['pgwui']
    menu_items = []
    if 'order' in pgwui['pgwui_menu']:
        for component in pgwui['pgwui_menu']['order']:
            build_menu(request, pgwui, menu_items, component)
            components.remove(component)

    # Sort un-ordered menu items by pgwui component name, for lack of
    # anything better at present.
    components.sort()
    for component in components:
        build_menu(request, pgwui, menu_items, component)
    return menu_items


@view_config(route_name='pgwui_menu',
             renderer='pgwui_menu:templates/menu.mak')
@base_view
def menu_view(request):
    response = dict()

    components = plugin.find_pgwui_components()
    response['menu_items'] = build_menu_items(request, components)
    response['pgwui_menu'] = request.registry.settings['pgwui']['pgwui_menu']
    return response
