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

static spComponent quit_menu = NULL;

static void helloCB(spComponent component, void *data)
{
    static int count = 0;

    if (count >= 1) {
        if (spQuitPrompt(component) == SP_TRUE) {
            /* quit program */
            spQuit(0);
        } else {
            /* change label */
            spSetParams(component, SppTitle, "Hello World", NULL);
            count = 0;
        }
    } else {
        /* change label */
        spSetParams(component, SppTitle, "Goodbye World", NULL);
        count++;
    }
    
    return;
}

static void menuCB(spComponent component, void *data)
{
    spBool set;
    
    if (spGetToggleState(component, &set)) {
        if (set == SP_TRUE) {
            spMapComponent(quit_menu);
        } else {
            spUnmapComponent(quit_menu);
        }
    }
    
    return;
}

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

    /*spSetDebugLevel(100);*/
    
    /* initialize toolkit */
    toplevel = spInitialize(&argc, &argv, NULL);
    
    /* create main window */
    frame = spCreateMainFrame("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, "Hello World",
                  SppCallbackFunc, helloCB,
                  NULL);
    
    /* add menu separator */
    spAddMenuSeparator(menu, "menuSeparator1", NULL);

    /* add menu item */
    spAddCheckBoxMenuItem(menu, "Show Quit Menu",
                          SppCallbackFunc, menuCB,
                          SppSet, SP_TRUE,
                          NULL);
    
    /* add menu item */
    quit_menu = spAddMenuItem(menu, "Quit",
                              SppCallbackFunc, spQuitCB,
                              SppShortcut, "A-q",
                              NULL);

    /* create help menu */
    menu = spCreatePulldownMenu(menu_bar, "Help",
                                SppMenuHelp, SP_TRUE,
                                NULL);
    
    /* add menu item */
    spAddMenuItem(menu, "About",
                  SppCallbackFunc, spDisplayInformationCB,
                  SppCallbackData, "Menu version 1.0\nA menu demo using spComponent",
                  NULL);

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

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