/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>

#include <czmq.h>

#ifdef _WIN32
#define THREADID GetCurrentThreadId
#else
#define THREADID pthread_self
#endif

#define TEST2_DONE "__DONE__"

#define TEST1_ACK "__ACK__"
#define TEST1_DONE "__DONE__"

struct context
{
    zactor_t *actor;
};

typedef struct context context_t;

void test2(zsock_t *pipe, void *args)
{   
    zactor_t *sender;
    int done;
    char *msg;
    zsock_signal(pipe, 0);
    done = 0;
    while(!done)
    {
        msg = zstr_recv(pipe);
        if(strcmp(msg, TEST2_DONE) == 0 || strcmp(msg, "$TERM") == 0)
        {
            done = 1;
        }
        else
        {
            printf("Test2: %s (thread: %d)\n", msg, THREADID());
            sender = ((context_t *)args)->actor;
            zstr_send(sender, TEST1_ACK);
        }
        zstr_free(&msg);
    }
}

void test1(zsock_t *pipe, void *args)
{   
    zactor_t *test2_actor;
    int done;
    char *msg;
    test2_actor = zactor_new(test2, args);
    zsock_signal(pipe, 0);
    done = 0;
    while(!done)
    {
        msg = zstr_recv(pipe);
        if(strcmp(msg, TEST1_ACK) == 0)
        {
            printf("Test1: ACK from Test2 (thread: %d)\n", THREADID());
        }
        else if(strcmp(msg, TEST1_DONE) == 0 || strcmp(msg, "$TERM") == 0)
        {
            zstr_send(test2_actor, TEST2_DONE);
            done = 1;
            zactor_destroy(&test2_actor);
        }
        else
        {
            printf("Test1: %s (thread: %d)\n", msg, THREADID());
            zstr_send(test2_actor, msg);
        }
        zstr_free(&msg);
    }
}

int main(void)
{
    context_t ctx;
    zactor_t *test1_actor;
    printf("main (thread: %d)\n", THREADID());
    test1_actor = zactor_new(test1, &ctx);
    ctx.actor = test1_actor;
    zstr_send(test1_actor, "Hello world!");
    zstr_send(test1_actor, "Hello world!");
    zstr_send(test1_actor, "Hello world!");
    zclock_sleep(100);
    zstr_send(test1_actor, TEST1_DONE);
    zactor_destroy(&test1_actor);
    return 0;
}
