#pragma once
#include "..\socket\HP-Socket\Src\TcpServer.h"
#include "..\socket\HP-Socket\Src\SocketInterface.h"
#include "timer.hpp"
#include <string>
#include <deque>
#include <vector>
#include <map>
#include "threadsafe_queue.hpp"
using namespace std;
#include "json.hpp"
using json = nlohmann::json;
struct TCP_MSG
{
	CONNID dwConnID;
	std::string userId;
	int			type;
	std::string msg;
	char flag;
	std::vector<string> deal_msg;
	std::chrono::high_resolution_clock::time_point tp;
	std::string ip;
};


class CTcpServerProcess:public CTcpServerListener
{
public:
	CTcpServerProcess();
	~CTcpServerProcess();
public:
	void Send(CONNID dwConnID,LPCSTR msg);
	void Send(CONNID dwConnID, const BYTE* pBuffer, int iLength);
	void WaitRecvEvent();
	void SetRecvEvent();
	bool ReadMsg(std::vector<string> &vec, CONNID & dwConnID, int &flag, std::string &ip,std::string &userId);
	void CloseClient(CONNID dwConnID);
	int Start();
	void Stop();
	void SetServerPort(int port) { m_port=port; }
	void SetAddr(std::string addr) { m_addr= addr; }
	void BroadMsg(json broadmsg);
	void BroadMsg(const BYTE* pBuffer, int iLength);
	//bool UpdateConnID(std::string &addr, CONNID & dwConnID);
	std::string WChar2Ansi(std::wstring wstr);
	void WaitconnidEvent();
	void SetconnidEvent();
	bool GetConnid(std::string addr, CONNID &dwConnID);
	int  GetConnectionCount();
	void CloseConnect();
	void CloseConnect(CONNID dwConnID);
	void DeleteInfo(CONNID dwConnID);
	std::map<std::string, CONNID> m_userIdInfo;
	CTcpServer					m_server;
private:
	virtual EnHandleResult OnPrepareListen(ITcpServer* pSender, SOCKET soListen);
	virtual EnHandleResult OnAccept(ITcpServer* pSender, CONNID dwConnID, SOCKET soClient);
	virtual EnHandleResult OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
	virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
	virtual EnHandleResult OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
	virtual EnHandleResult OnShutdown(ITcpServer* pSender);
private:
	
	std::deque<CONNID>			m_de_connid;
	std::map<CONNID, TCP_MSG>	m_tcpmsg;
	std::map<std::string, CONNID>	m_tcpaddr_connid;
	typedef std::map<CONNID, TCP_MSG>::iterator Iter;
	typedef std::map<std::string, CONNID>::iterator AddrIter;
	std::mutex					m_muter_tcp;
	std::mutex					m_muter_addr;
	HANDLE						m_reve_event;
	HANDLE						m_connid_event;
	std::string					m_addr;
	int							m_port;
	std::deque<TCP_MSG>			m_rcvmsg;
	threadsafe_queue<TCP_MSG*>	m_safemsg;
	tools::tim::timer			m_timer;

};

