import re
import json


def get_pagetext_links(pagetext):
    """Get all page links from current page's pagetext.

    Args:
        pagetext (string): HTML to be searched through
    Returns:
        (dict): Pagetext links like {Category: {Pagename: URL}, ...}
    """
    json_text = re.findall(
        r'window\.initializeSideNavigation\([ -(*-~\r\n]*\)',
        pagetext)[0][69:-10]
    json_dict = json.loads(json_text)
    # Format of this dict: {tab_menu: {tab: {'url': val, 'name': val}, ...
    page_url_dict = {}
    for tab_menu in range(len(json_dict['tab_menu']['tabs'])):
        tab_menu = json_dict['tab_menu']['tabs'][tab_menu]
        category = tab_menu['name']
        page_url_dict[category] = {}
        for menu in ('Monitor', 'Configure'):
            # Cameras do not have a configure section.
            if not (category == 'Cameras' and menu == 'Configure'):
                menu_items = tab_menu['menus'][menu]['items']
                for tab_index, _ in enumerate(menu_items):
                    # Sometimes a tab JSON is Null, in which case skip it.
                    if menu_items[tab_index]:
                        name = menu_items[tab_index]['name']
                        url = menu_items[tab_index]['url']
                        page_url_dict[category][name] = url

    return page_url_dict