#pragma once

#pragma comment(lib, "Ws2_32.lib")

extern "C"{
#include "mongoose.h"
}

#include <functional>
#include <memory>

namespace mjz{
	class MsgDispatcher;
}


typedef std::function<void(bool succ)> connect_cb;
typedef std::function<void(const std::string& data)> receive_cb;
typedef std::function<void()> brocken_cb;

struct ws_cb
{
	connect_cb on_connect;
	receive_cb on_received;
	brocken_cb on_broken;
};

class game_websocket_client
{
public:
	game_websocket_client();
	~game_websocket_client();

	bool start_websocket(const std::wstring& openid, const std::wstring& port, connect_cb on_connect, receive_cb on_received, brocken_cb on_broken);
	bool send_data(const std::string& data);
	bool is_connected();

	static void callback(struct mg_connection *c, int ev, void *ev_data, void *fn_data);
	void handle_event(struct mg_connection *c, int ev, void *ev_data);

private:

	// 线程再封装一层，方便代码移植修改
	void run_in_main_thread(std::function<void()>&& func);
	void run_in_separate_thread(std::function<void()>&& func);


private:
	mg_mgr m_mg_mgr;
	mg_connection *m_mg_c = nullptr;
	ws_cb m_ws_cb;

	std::shared_ptr<mjz::MsgDispatcher>  m_msg_dispatcher = nullptr;
	std::string m_ws_url;
};
