#include <stdio.h>
#include <sp/spBaseLib.h>
#include <sp/spComponentLib.h>
#include <sp/spComponentMain.h>

static void displayPluginInfoCB(spComponent component, char *plugin_name)
{
    char *information;
    spPlugin *plugin;

    /* load plugin */
    if ((plugin = spLoadPlugin(plugin_name)) != NULL) {
        information = spGetPluginInformation(plugin);
        
        spDisplayInformation(/*component*/NULL, NULL, information);
        
        spFreePlugin(plugin);
    }
    
    return;
}

static void createPluginInfoMenu(spComponent sub_menu)
{
    int i;
    char *plugin_name;
    spComponent menu_item;
    spPlugin *plugin;
    
    for (i = 0;; i++) {
        if ((plugin_name = xspSearchPluginFile(i)) == NULL) {
            break;
        }
        if ((plugin = spLoadPlugin(plugin_name)) != NULL) {
            menu_item = spAddMenuItem(sub_menu, "pluginInfoMenu",
                                      SppTitle, spGetPluginDescription(plugin),
                                      SppCallbackFunc, displayPluginInfoCB,
                                      SppCallbackData, plugin_name,
                                      NULL);
            spFreePlugin(plugin);
        }
    }
    
    return;
}

int spMain(int argc, char *argv[])
{
    spTopLevel toplevel;
    spComponent frame;
    spComponent menu_bar;
    spComponent menu, help_menu;
    spComponent sub_menu;

    spSetDebugLevel(100);
    
    /* initialize toolkit */
    toplevel = spInitialize(&argc, &argv, NULL);
    
    /* create main window */
    frame = spCreateMainFrame("Plug-in Menu", NULL);
    
    /* create menu bar */
    menu_bar = spCreateMenuBar(frame, "menuBar",
                               SppTitle, "Menu Bar",
                               NULL);
    
    /* create menu */
    menu = spCreatePulldownMenu(menu_bar, "Menu", NULL);
    
    /* add menu item */
    spAddMenuItem(menu, "Quit",
                  SppCallbackFunc, spQuitCB,
                  NULL);

    /* create help menu */
    help_menu = spCreatePulldownMenu(menu_bar, "Help",
                                     SppMenuHelp, SP_TRUE,
                                     NULL);
    
    /* add menu item */
    spAddMenuItem(help_menu, "About",
                  SppCallbackFunc, spDisplayInformationCB,
                  SppCallbackData, "Plugin Menu version 1.0\nA menu listing plug-ins demo using spComponent",
                  NULL);
    
    /* add plugin menu */
    sub_menu = spAddSubMenu(help_menu, "pluginInfo",
                            SppTitle, "Plugin Information",
                            NULL);
    createPluginInfoMenu(sub_menu);

    /* create push button */
    spCreatePushButton(frame, "Quit",
                       SppCallbackFunc, spQuitCB,
                       SppInitialWidth, 200,
                       NULL);

    /* popup window */
    spPopupWindow(frame);
    
    /* main loop */
    return spMainLoop(toplevel);
}
