/*
 * Test for timer code
 */

#include <stdio.h>
#include "event.h"


class timerA : public timerhandler {
public:
  timerA() : timerhandler(STATIC) {}
  void tick(eventloop *src, timeval t) {
    printf("(A:%p) Tick (%ld,%ld)\n", this, t.tv_sec, t.tv_usec);
  }
};

class timerB : public timerhandler {
  int *flag;
public:
  timerB(int *exitflag) : timerhandler(STATIC), flag(exitflag) {}
  void tick(eventloop *src, timeval t) {
    printf("(B:%p) Tick (%ld,%ld), setting exit flag\n", this, t.tv_sec,
           t.tv_usec);
    (*flag)++;
  }
};

class canceller : public timerhandler {
  eventloop *loop;
  int id;
public:
  canceller(eventloop *eloop, int timer_id) : timerhandler(DYNAMIC),
	loop(eloop), id(timer_id) {}
  ~canceller() {
    printf("The reaper departs!\n");
  }
  void tick(eventloop *src, timeval t) {
    printf("Cancelling timer %d\n", id);
    loop->unschedule(id);
  }
};

int main() {
  eventloop loop;
  int quitflag=0;
  timerA x, y;
  timerB z(&quitflag);
  canceller *reaper;
  int xid, yid, zid;

  xid=loop.schedule(10,0, &x);		// tick once after 10 seconds
  yid=loop.schedule(1,0, 2,0, &y);	// tick after 1 second, and every 2
					// seconds thereafter
  zid=loop.schedule(30,0, &z);		// tick after 30 seconds and set
					// quit flag

  reaper = new canceller(&loop, yid);
  loop.schedule(25,0, reaper);		// kill timer y after 25 seconds

  // Begin the fun!
  loop.run(&quitflag);
}

