#include "stdafx.h"
#include "TcpClient.h"
#include <iostream>
#include "../../HPSocket/Include/HPSocket/HPSocket.h"
#include "../Log/LogMgr.h"
#include "../TradeApi/TradeApi.h"


CNetTcpClientListener::CNetTcpClientListener()
{
	m_bMultiPacks = FALSE;
	m_str = "";
	m_nLenTotal = 0;
	m_nLenRecv = 0;
	m_nPackgeId = 0;
}
CNetTcpClientListener::~CNetTcpClientListener()
{

}

EnHandleResult CNetTcpClientListener::OnPrepareConnect(ITcpClient* pSender, CONNID dwConnID, SOCKET socket)
{
	//cout << "OnPrepareConnect" << endl;
	return HR_OK;
}
EnHandleResult CNetTcpClientListener::OnSend(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
	return HR_OK;
}

int CNetTcpClientListener::OnReadHead(void* pData, int nLen)
{
	return -1;
}

bool IsFullPackage(const BYTE* pData, int iLength)
{
	return false;
}

int CNetTcpClientListener::SwapInt(int value)
{
	return ((value & 0x000000FF) << 24) |
		((value & 0x0000FF00) << 8) |
		((value & 0x00FF0000) >> 8) |
		((value & 0xFF000000) >> 24);
}

int CNetTcpClientListener::HandlerPack(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
	return -1;
}

EnHandleResult CNetTcpClientListener::OnReceive(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
	string sRecv((char*)pData, iLength);
	TRADE_API->OnReadData(pData, iLength);
	return HR_OK;
}
EnHandleResult CNetTcpClientListener::OnClose(ITcpClient* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
	cout << "OnClose" << endl;
	return HR_OK;
}
EnHandleResult CNetTcpClientListener::OnConnect(ITcpClient* pSender, CONNID dwConnID)
{
	cout << "OnConnect"<< endl;
	return HR_OK;
}

EnHandleResult CNetTcpClientListener::OnShutdown(ITcpServer* pSender)
{
	cout << "OnShutdown" << endl;
	return HR_OK;
}

CTcpClient::CTcpClient()
{
}


CTcpClient::~CTcpClient()
{
	m_pTcpClient->Stop();
	HP_Destroy_TcpClient(m_pTcpClient);
}

void CTcpClient::Init(string strHost, int nPort)
{
	if (m_pTcpClient!=nullptr)
	{
		m_pTcpClient->Stop();
		HP_Destroy_TcpClient(m_pTcpClient);
	}
	char sMsg[200] = {0};
	sprintf_s(sMsg, "start connect %s:%d", strHost.c_str(), nPort);
	cout << sMsg << endl;
	X_INFO(sMsg);
	m_pTcpClient = HP_Create_TcpClient(&m_TcpClientListener);
	m_bConnected = m_pTcpClient->Start((LPCTSTR)strHost.c_str(), nPort, FALSE);
	if (m_bConnected)
	{
		cout << "connect success" << endl;
		X_INFO("connect success");
	}

	else
	{
		cout << "connect failed" << endl;
		X_ERR("connect failed");
	}

}
void CTcpClient::SendMsg(char* pBuf,int nLen)
{
	if (m_pTcpClient == nullptr) return;
	if (nLen <= 0) return;
	TRADE_API->m_nPakgeId++;
	m_pTcpClient->Send((BYTE*)pBuf, nLen);
}
