#include "piobject.h"
#include "pitime.h"

#include "gtest/gtest.h"

std::atomic<int> obj_cnt;

class Send: public PIObject {
	PIOBJECT(Send)

public:
	Send() { obj_cnt++; }
	~Send() { obj_cnt--; }
	EVENT1(ev, PIObject *, o)
};


class Recv: public PIObject {
	PIOBJECT(Recv)

public:
	Recv() { obj_cnt++; }
	~Recv() { obj_cnt--; }
	EVENT_HANDLER1(void, eh, PIObject *, o) {
		o->deleteLater();
		piMSleep(10);
	}
};


TEST(Piobject, deleteLater) {
	obj_cnt  = 0;
	Send * s = new Send();
	Recv * r = new Recv();
	CONNECTU(s, ev, r, eh);
	s->ev(r);
	r->deleteLater();
	s->deleteLater();
	piMSleep(100);
	ASSERT_EQ(obj_cnt, 0);

	PIVector<Send *> s2;
	s2.resize(100, new Send());
	for (auto o: s2)
		o->deleteLater();
	piMSleep(10);
	ASSERT_EQ(obj_cnt, 0);
	s2.clear();

	PIVector<Recv *> r2;
	r2.resize(100, [](size_t i) { return new Recv(); });
	for (auto o: r2)
		o->deleteLater();
	piMSleep(10);
	ASSERT_EQ(obj_cnt, 0);
	r2.clear();
}
