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

static int click_count = 0;

static spBool toplevelCB(spTopLevel toplevel, spTopLevelCallbackReason reason, void *data)
{
    spDebug(10, "toplevelCB", "reason = %d\n", reason);
    return SP_TRUE;
}

static void pressCB(spComponent component, void *data)
{
    if (spGetCallbackReason(component) == SP_CR_BUTTON_PRESS) {
        spDebug(10, "pressCB", "pressed\n");
        printf("pressed\n");
    } else {
        spDebug(10, "pressCB", "released\n");
        printf("relased\n");
    }
    
    return;
}

static void helloCB(spComponent component, void *data)
{
    if (click_count >= 1) {
        if (spQuitPrompt(component) == SP_TRUE) {
            /* quit program */
            spDebug(10, "helloCB", "call spQuit\n");
            spQuit(0);
        } else {
            /* change label */
            spSetParams(component, SppTitle, "Hello World", NULL);
            click_count = 0;
        }
    } else {
        /* change label */
        spSetParams(component, SppTitle, "Goodbye World", NULL);
        click_count++;
    }
    
    spDebug(50, "helloCB", "done\n");
    
    return;
}

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

    /*spSetDebugLevel(100);*/

    click_count = 0;
    
    /* initialize toolkit */
    toplevel = spInitialize(&argc, &argv,
                            SppTopLevelCallbackFunc, toplevelCB,
                            NULL);
    
    /* create main window */
    frame = spCreateMainFrame("HelloCB", NULL);

    /* create push button */
    button = spCreatePushButton(frame, "Hello World",
                                SppCallbackFunc, helloCB,
                                SppInitialWidth, 200,
                                NULL);
    spAddCallback(button, SP_BUTTON_PRESS_CALLBACK | SP_BUTTON_RELEASE_CALLBACK, pressCB, NULL);

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