#ifndef CDUTILS_CORE_H
#define CDUTILS_CORE_H

#include "cdutils_types.h"
#include "cdutils_protocol.h"
#include "piconnection.h"
#include "pidatatransfer.h"


namespace CDUtils {

class CDCore;


class __Core_Initializer__ {
public:
	__Core_Initializer__();
	~__Core_Initializer__();
	static int count_;
	static CDCore * __instance__;
};


class CDCore: public PIObject
{
	PIOBJECT(CDUtils::CDCore)
	friend class __Core_Initializer__;
	friend class CDSection;
	friend class KInterface;
public:
	static CDCore * instance();

	EVENT(K_Sended)
	EVENT(K_SendFail)
	EVENT(K_Received)
	EVENT(K_ReceiveFail)
	EVENT(K_ChangedGlobal)
	EVENT_HANDLER(void, K_Send);
	EVENT_HANDLER(void, K_Request);

	void k_write(PIIODevice * d);
	void k_read(PIIODevice * d);
	void k_parse(PIIODevice * d);
	void k_update(PIIODevice * d, UpdateModeFlags mode);
	void k_calculate();
	void initApp();
	void initPult();
	void init(const PIString & configuration);
	void startPing();
	bool inProgress() {return sendt.isRunning();}

	CDSection & k() {return k_;}

	static PIString pultConfig() {return PIString(pult_config);}
	static PIString appConfig() {return PIString(app_config);}

private:
	CDCore();
	~CDCore();
	EVENT_HANDLER2(void, dataReceived, const PIString &, from, const PIByteArray &, data);
	EVENT_HANDLER1(void, dtSendRequest, PIByteArray &, data);
	EVENT_HANDLER1(void, dtReceiveFinished, bool, ok);
	EVENT_HANDLER(void, sendThread);
	EVENT_HANDLER(void, xTimerTick);
	void initRoot(CDSection & r);

	static const char app_config[], pult_config[];
	PIConnection connection;
	PIDataTransfer datatr;
	PacketHeader wheader;
	PIByteArray send_data;
	PIThread sendt;
	PITimer x_timer;
	CDSection k_;

};


static __Core_Initializer__ __Core_initializer__;

}

#endif // CDUTILS_CORE_H
