/* COMPILE WITH:
 * valac -X -DGMENU_I_KNOW_THIS_IS_UNSTABLE --pkg libgnome-menu menutest.vala
 */
namespace MenuTest
{
  static GMenu.Tree tree;
  static uint tree_changed_timeout = 0;

  public static int main (string[] args)
  {
    tree = GMenu.Tree.lookup ("applications.menu",
                              GMenu.TreeFlags.NONE);
    
    tree.add_monitor ((menu) => {
            /* Reschedule the timeout if we already have one. The menu tree triggers
             * many change events during app installation. This way we wait the full
             * delay *after* the last change event has triggered */
            if (tree_changed_timeout != 0)
              Source.remove (tree_changed_timeout);
            
            tree_changed_timeout = Timeout.add_seconds (5, list_menu_tree);
    });
    
    list_menu_tree ();
    new MainLoop().run();
    
    return 0;
  }
  
  private bool list_menu_tree ()
  {
    print ("MENU TREE:\n*************\n");
    list_menu_item (tree.get_root_directory ());
    return false;
  }
  
  private void list_menu_item (GMenu.TreeItem item)
  {
    switch (item.get_type ())
	    {
	      case GMenu.TreeItemType.INVALID:
	        warning ("INVALID ITEM TYPE");
	        return;
	      case GMenu.TreeItemType.DIRECTORY:
	        /* Recurse into directory */
	        unowned SList<GMenu.TreeItem> contents = ((GMenu.TreeDirectory) item).get_contents ();
	        print (" DIRECTORY %s\n", ((GMenu.TreeDirectory) item).get_desktop_file_path ());
	        foreach (var _item in contents)
	          list_menu_item (_item);
	        break;
	      case GMenu.TreeItemType.ENTRY:
	        print (" * %s\n", ((GMenu.TreeEntry) item).get_desktop_file_path ());
	        break;
	      case GMenu.TreeItemType.SEPARATOR:
	      case GMenu.TreeItemType.HEADER:
	      case GMenu.TreeItemType.ALIAS:
	        break;
	      default:
	        warning ("Unexpected GMenuTreeItemType %u", item.get_type ());
	        return;
      }
  }
}
