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

static spBool non_blocking = SP_FALSE;
static spComponent text = NULL;

static void checkBoxCB(spComponent component, int num)
{
    spBool set;
    
    if (spGetToggleState(component, &set)) {
        if (set == SP_TRUE) {
            non_blocking = SP_TRUE;
        } else {
            non_blocking = SP_FALSE;
        }
    }
    
    return;
}

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

    /* initialize toolkit */
    toplevel = spInitialize(&argc, &argv,
                            /*SppThreadSafe, SP_TRUE,*/
                            NULL);
    
    /* create main window */
    frame = spCreateMainFrame("Loop Test", NULL);

    /* create menu bar */
    menu_bar = spCreateMenuBar(frame, "menuBar", NULL);
    
    /* create menu */
    menu = spCreatePulldownMenu(menu_bar, "fileMenu",
                                SppTitle, "File",
                                NULL);
    
    /* add menu item */
    spAddMenuItem(menu, SP_QUIT_MENU_ITEM_NAME,
                  SppCallbackFunc, spQuitCB,
                  SppTitle, "Quit",
                  SppShortcut, "A-q",
                  NULL);

    /* create check box */
    spCreateCheckBox(frame, "Non-Blocking Mode",
                     SppCallbackFunc, checkBoxCB,
                     SppCallbackData, 1,
                     NULL);

    /* create text field */
    text = spCreateTextField(frame, "text",
                             SppEditable, SP_FALSE,
                             NULL);

    /* popup window */
    spPopupWindow(frame);
    
    /* main loop */
    for (i = 0;; i++) {
        if (non_blocking == SP_TRUE) {
            spDispatchEvent(toplevel);
        } else {
            spWaitNextEvent(toplevel);
        }
        
        if (i >= 4) {
            i = 0;
        }
        if (i == 0) {
            spSetTextString(text, "/(;_;)\\");
        } else if (i == 1) {
            spSetTextString(text, "_(o_o)_");
        } else if (i == 2) {
            spSetTextString(text, "_(^_^)_");
        } else if (i == 3) {
            spSetTextString(text, "\\(^o^)/");
        }
    }

    return 0;
}
