#pragma once
#include "Protocol.h"

#define BUFSIZE 4096
typedef struct _PER_IO_CONTEXT
{
	OVERLAPPED	m_Overlapped;
	BYTE		szBuffer[BUFSIZE];
	DWORD		dwBufferSize;

	_PER_IO_CONTEXT()
	{
		dwBufferSize = 0;
		memset(&m_Overlapped, 0, sizeof(OVERLAPPED));
		memset(szBuffer, 0, BUFSIZE);
		m_Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	}

	~_PER_IO_CONTEXT()
	{
		if ( m_Overlapped.hEvent != NULL )
		{
			SetEvent(m_Overlapped.hEvent);
			CloseHandle(m_Overlapped.hEvent);
		}
	}
}PER_IO_CONTEXT, *PPER_IO_CONTEXT;

// 连接成功时,向服务器发送消息;
typedef BOOL(CALLBACK* OnConnected)();

class CPipeClient
{
public:
    // 客户端只有PIPE_READMODE_BYTE PIPE_READMODE_MESSAGE两种模式;
    CPipeClient(LPCTSTR lpPipeName, DWORD dwMode=PIPE_READMODE_MESSAGE);
    ~CPipeClient(void);

private:
	// 管道句柄;
    HANDLE m_hPipeInst;
    // 客户端状态;
    BOOL m_bClientStop;
    // 管道名称;
    TCHAR m_szPipeName[MAX_PATH];
    // 管道通信模式;
    DWORD m_dwMode;

	static std::string m_LastData;
	static PER_IO_CONTEXT m_IoRead;
	// Write使用同步方式;
	static PER_IO_CONTEXT m_IoWrite;
public:
    BOOL StartWork();
    void StopWork() { m_bClientStop = TRUE;Sleep(100000);}
    // 连续管道服务器线程;
    static DWORD WINAPI ConnectThread(LPVOID lpParam);
    // 读取管道消息线程;
    static DWORD WINAPI ReadMsgThread(LPVOID lpParam);
	// 等待重叠IO完成;
	static BOOL WaitFinish(HANDLE hPipe, PER_IO_CONTEXT *pIoContext);
	// 处理消息;
	static void HandleMsg(DATAHEADER &head, MSG_INFO &msg);
	// 发送消息给服务端;
	BOOL SendPackage(PACKAGE &pak);
	BOOL SendPackage(DATAHEADER &head, MSG_INFO &msg);

protected:
	BOOL SendData(LPBYTE lpData, DWORD dwDataLen);
};
