#include "cdutils_k.h"
#include "cdutils_x.h"
#include "cdutils_c.h"
#include "cdutils_m.h"
#include "cdutils_core.h"
#include "cdtest.h"
#include "pip.h"
#include "k_description.h"

using namespace CDUtils;

class Core : public PIObject
{
	PIOBJECT(Core)
	public:
		Core() {
		CDCore::instance()->initApp();
//		piCout << "testCore";
		CONNECTU(&timer, tickEvent, this, timerDone);
		CONNECTU(&X, received, this, xrecv);
		CONNECTU(&C, received, this, crecv);
		t = 0.;
	}

	void load() {
		rf.open("k.dat", PIIODevice::ReadWrite);
		K.read(&rf);
		rf.close();
	}

	void save() {
		rf.open("k_out.txt", PIIODevice::ReadWrite);
		rf.resize(0);
		K.write(&rf);
		rf.close();
//		rf.open("k_out.txt", PIIODevice::ReadWrite);
//		K.read(&rf);
//		rf.close();
//		rf.open("k_out2.txt", PIIODevice::ReadWrite);
//		rf.resize(0);
//		K.write(&rf);
//		rf.close();
//		rf.open("k_out2.txt", PIIODevice::ReadWrite);
//		K.read(&rf);
//		rf.close();
//		rf.open("k_out3.txt", PIIODevice::ReadWrite);
//		rf.resize(0);
//		K.write(&rf);
//		rf.close();
	}

	void test() {
		X.lock();
		X[KD::Frequency] = 100;
		X.section(KD::Spectrometer)[KD::Temperature_default] = sin(t);
		t += 0.01;
		X.unlock();
		/*piCout << "count" << K.count();
		piCout << K[First];
		piCout << K[Second];*/
	}

	EVENT_HANDLER(void, ksend) {piCout << "sended k";}
	EVENT_HANDLER(void, crecv) {
		piCout << "received c";
		C.connect(C.section(KD::Logs).section(KD::Spec).section(KD::Formats)[KD::Binary], this, HANDLER(cmd));
		C.autoConnect(this);
	}
	EVENT_HANDLER(void, xrecv) {
		piCout << "received x";
		if (!timer.isRunning()) timer.start(10);
		X.start();
	}
	EVENT_HANDLER(void, timerDone) {test();}
	EVENT_HANDLER(void, cmd) {piCout << "command cmd";}
	EVENT_HANDLER(void, c_Pause) {
		piCout << "command pause";
		M[KD::Main] << "rec command" << C[KD::Pause];
		M.messageBox(M.root()[KD::Core], "init successfull");
	}
	EVENT_HANDLER(void, c_Spectrometer_Connection) {piCout << "command spec_conn";}

private:
	PIFile rf;
	PITimer timer;
	double t;
};


int main(int argc, char *argv[]) {
	X.start();
	piSleep(1);
	//CDCore::instance()->destroy();
	piCout << "DELETED";
	return 0;
}

