#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

#define IMP
#include "./future.h"

struct counter {
	uint32_t count;
	uint32_t end;
};

void *counter_future(void *env, void *data);
struct future counter_then(void *env, void *result);

int
main(int argc, char *argv[])
{
	struct future counter_f1 = {0};
	struct future counter_f2 = {0};
	struct counter c1 = {0, 5};
	struct counter c2 = {5, 10};

	counter_f1.f = &counter_future;
	counter_f1.env = &c1;
	counter_f1.then = counter_then;
	counter_f2.f = &counter_future;
	counter_f2.env = &c2;

	while ( true ) {
		void *r1 = NULL;
		void *r2 = NULL;
		r1 = future_poll(&counter_f1, NULL, NULL);
		r2 = future_poll(&counter_f2, NULL, NULL);
		if ( r1 != NULL && r2 != NULL ) {
			break;
		}
	}

	(void) argc; (void) argv;
	return 0;
}

void *
counter_future(void *env, void *data)
{
	struct counter *this = (struct counter *) env;
	if ( this->count >= this->end ) {
		return &this->count;
	}

	printf("Counted: %d\n", this->count);
	++this->count;

	(void) data;
	return NULL;
}

struct future
counter_then(void *env, void *result)
{
	struct future ftr = {0};
	struct counter *c = (struct counter *)env;
	uint32_t res = *(uint32_t *) result;

	printf("\t\tResult: %d\n", res);

	c->count += 5;
	c->end += 10;
	ftr.f = counter_future;
	ftr.env = c;
	if ( res < 35 ) {
		ftr.then = counter_then;
	}
	return ftr;
}
