#include "include/ipclib.h"

#include <memory>
#include <assert.h>

#include "Ipc.h"
#include "ReadCallback.h"

class ReaderCallback : public IReaderCallback {
public:
	ReaderCallback() = default;
	~ReaderCallback() override = default;
	void onRead(const char* buffer, unsigned int size) override {
		printf("%s", buffer);
		if (nullptr != m_readerCallbackFunc) {
			m_readerCallbackFunc(buffer, size);
		}
	}

	void setCallback(ReaderCallbackFunc func) {
		m_readerCallbackFunc = func;
	}

private:
	ReaderCallback(const ReaderCallback&) = delete;
	ReaderCallback operator= (const ReaderCallback&) = delete;

private:
	ReaderCallbackFunc m_readerCallbackFunc{nullptr};
};

std::shared_ptr<Ipc> g_ipc;
std::shared_ptr<ReaderCallback> g_readCallback;

bool __stdcall initialize(const char* sender_name, const char* receiver_name) {
	assert(!g_ipc);
	g_ipc = Ipc::create(sender_name, receiver_name);
	return true;
}

 void __stdcall uninitialize() {
	 assert(g_ipc);
	 g_ipc->stop();
	 if (g_readCallback) {
		 g_ipc->unregistReadCallback(g_readCallback);
		 g_readCallback.reset();
	 }
	 g_ipc.reset();
}

 void __stdcall reConnect() {
     assert(g_ipc);
     return g_ipc->reConnect();
 }

bool __stdcall listen() {
	assert(g_ipc);
	return g_ipc->listen();
 }

 bool __stdcall send(const char* data, unsigned int size) {
	 assert(g_ipc);
	 return g_ipc->send(data, size);
 }

 bool __stdcall setReaderCallback(ReaderCallbackFunc callback) {
	 assert(g_ipc);
	 if (!g_readCallback) {
		g_readCallback = std::make_shared<ReaderCallback>();
		g_ipc->registReadCallback(g_readCallback);
	}
	 g_readCallback->setCallback(callback);
	 return true;
 }
