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

using namespace std;

#include "caf/all.hpp"

using namespace caf;

#ifdef _WIN32
#define THREADID_T int
#define THREADID GetCurrentThreadId
#define SLEEP_MULT 1000
#define SLEEP Sleep
#else
#define THREADID_T pthread_t
#define THREADID pthread_self
#define SLEEP_MULT 1
#define SLEEP sleep
#endif
extern "C"
{
    THREADID_T THREADID();
    void SLEEP(int t);
}

CAF_BEGIN_TYPE_ID_BLOCK(demo, first_custom_type_id)
  CAF_ADD_ATOM(demo, test2_done)
  CAF_ADD_ATOM(demo, test1_ack)
  CAF_ADD_ATOM(demo, test1_done)
CAF_END_TYPE_ID_BLOCK(demo)

void test2(blocking_actor* self)
{
    bool run = true;
    self->receive_while(run)(
        [&](test2_done)
        {
            run = false;
        },
        [&](const string& msg)
        {
            aout(self) << "test2: " << msg << " (thread: " << THREADID() << ")" << endl;
            self->send(actor_cast<event_based_actor*>(self->current_sender()), test1_ack_v);
        }
    );
}

class test2_actorclass : public blocking_actor {
    public:
        test2_actorclass(actor_config& cfg) : blocking_actor(cfg) { }
        void act() override {
            return test2(this);
        }
};

void test1(blocking_actor* self)
{
    auto test2_actor = self->spawn<test2_actorclass>();
    bool run = true;
    self->receive_while(run)(
        [&](test1_ack)
        {
            aout(self) << "test1: ACK received"  << " (thread: " << THREADID() << ")" << endl;
        },
        [&](test1_done)
        {
            self->send(test2_actor, test2_done_v);
            run = false;
        },
        [&](const string& msg)
        {
            aout(self) << "test1: " << msg  << " (thread: " << THREADID() << ")" << endl;
            self->send(test2_actor, msg);
        }
    );
}

class test1_actorclass : public blocking_actor {
    public:
        test1_actorclass(actor_config& cfg) : blocking_actor(cfg) { }
        void act() override {
            return test1(this);
        }
};

void caf_main(actor_system& sys) {
    auto test1_actor = sys.spawn<test1_actorclass>();
    scoped_actor self { sys };
    aout(self) << "main (thread: " << THREADID() << ")" << endl;
    self->send(test1_actor, "Hello world!");
    SLEEP(1 * SLEEP_MULT);
    self->send(test1_actor, test1_done_v);
}

CAF_MAIN(id_block::demo)
