#pragma once

#include <thread>
#include <libipc/ipc.h>
#include <memory>
#include <atomic>
#include <string>
#include <mutex>

class IReaderCallback;

class Ipc : public std::enable_shared_from_this<Ipc>{
public:
	static std::shared_ptr<Ipc> create(const char* reader_name, const char* writer_name);
public:
	virtual ~Ipc();

	bool listen();
	void stop();
	bool send(const char* data, unsigned int size);
	void reConnect();

	void registReadCallback(const std::shared_ptr<IReaderCallback>& reader);
	void unregistReadCallback(const std::shared_ptr<IReaderCallback>& reader);

protected:
	Ipc(const char* reader_name, const char* writer_name) noexcept;

private:
	void doReciver(std::weak_ptr<Ipc> wThis);

	void onReciveer(const char* buffer, unsigned int size);

private:
	std::string reader_name_;
	std::string writer_name_;
	std::unique_ptr<ipc::channel> sender_;
	std::unique_ptr<ipc::channel> receiver_;
	std::thread reciver_thread_;
	std::atomic_bool reciver_stop_{false};

	std::mutex mutex_;
	using ReaderCallbackList = std::vector<std::shared_ptr<IReaderCallback>>;
	ReaderCallbackList reader_callbacks_;
};

