#include <stdio.h> 
#include <pthread.h>
#include <unistd.h>
#include <epp/epp.h>

/* Threaded async call example using EPP API */

void *thread(void *unused) {
    /* PAL: Attach Prolog Engine to this thread */
    pl_attach_engine();

    /* EPP: Process events */
    EPP_Process(-1, 0, 1, 0);

    /* PAL: Detach Prolog Engine from this thread */
    pl_detach_engine();
    return(NULL);
}


int callback(int retval, void *userdata) {
    static unsigned int call = 1;
    long *i = (long*) userdata;
    

    if (retval == PL_TRUE) {
	printf("<CALL %u> TRUE:\t %li\n", call++, *i);
    } else if (retval == PL_FALSE) {
	printf("<CALL %u> FALSE\n", call++);
    } else {
	printf("<CALL %u> ERROR\n", call++);
    }

    return(EPP_NEXT_SOLUTION);
}

int main(int argc, char *argv[]) {
    pthread_t t;
    long i;

    /* Initialise Prolog */
    pl_init_from_state(*argv);
    
    /* Create Processing Thread(s) */
    pthread_create(&t, NULL, thread, NULL);

    /* EPP: Make a call */
    epp_acall(callback, &i, 0, "counter", "I", &i);

    /* Give some time for processing thread (for request handling) */
    usleep(100*1000);
    
    /* Force exit from EPP_Process() */
    EPP_ProcessUnblockAll();

    /* Give some time for processing thread (for safe shutdown) */
    usleep(100*1000);
    
    /* Shutdown Prolog */
    pl_shutdown();
    return(0);
}
