#include <stdafx.h>
#include "CNet.h"
#include "blocksock.h"
#include <list>
#define REFRESH_INTERVAL 10000
using std::list;

const NETOBJ_HEADER disconn_header(-1,0);
const NETOBJ_HEADER refresh_header(-2,0);

//---------------------------------------------------------------------------------------------
//Name: Recv Thread Process
//Desc: Polling and recv data
//---------------------------------------------------------------------------------------------
UINT RecvThProc(LPVOID pParam){
	RECVTHREADPARAM* pRecvInfo = (RECVTHREADPARAM*) pParam;

	CBlockingSocket bSocket(pRecvInfo->hSocket);
	CNet* myNet = (CNet*)(pRecvInfo->pNet);
	int myID = pRecvInfo->ID;
	
	WSANETWORKEVENTS NetworkEvents;

	WSAEVENT EventArray[1];
	EventArray[0] = pRecvInfo->hEvent;
	WSAResetEvent(EventArray[0]);

	CSingleLock Slock(&myNet->m_csRecvCallback);
	char header_buf[sizeof(NETOBJ_HEADER)];

	delete pRecvInfo;

	while(1){
		WSAWaitForMultipleEvents(1, EventArray, FALSE, WSA_INFINITE, FALSE);
		WSAEnumNetworkEvents(bSocket.GetSocket(), EventArray[1], &NetworkEvents);
		
			WSAResetEvent(EventArray[0]);
			

			if(bSocket.Read(header_buf, sizeof(NETOBJ_HEADER)) == SOCKET_ERROR){
				myNet->DisConnectInRecv(myID);
				return 0;
			}

			NETOBJ_HEADER* header = (NETOBJ_HEADER*)header_buf;

			if(header->m_type == -1){		//close connection msg, disconnect
				myNet->DisConnectInRecv(myID);
				return 0;
			}
			else if(header->m_type == -2){	//refresh header, ignore
				continue;
			}
		
			char* pBuf = new char[header->m_length];

			if(bSocket.Read(pBuf, header->m_length) == SOCKET_ERROR){
				myNet->DisConnectInRecv(myID);
				return 0;
			}
		
			NETOBJ* pnetobj = new NETOBJ;
			pnetobj->m_header = *header;
			pnetobj->m_ID = myID;
			pnetobj->m_pBuf = pBuf;

			Slock.Lock();
			myNet->m_pHandler->OnRecv(pnetobj);
			Slock.Unlock();

			delete pnetobj;
		
		
	}
	return 0;
}


//---------------------------------------------------------------------------------------------
//Name: Refresh Thread
//Desc: Check all connection every REFRESH_INTERVAL minisec
//---------------------------------------------------------------------------------------------

UINT RefreshThProc(LPVOID pParam){
	CNet* myNet = (CNet*) pParam;
	while(1){
		myNet->Refresh();
		Sleep(REFRESH_INTERVAL);
	}
	return 0;
}

//---------------------------------------------------------------------------------------------
//Name: Listen Thread
//Desc: Listen Connection 
//---------------------------------------------------------------------------------------------

UINT LisThProc(LPVOID pNet){
	CNet *myNet  = (CNet *) pNet;
	CSingleLock Slock(&myNet->m_csSocketMap);
	while(1){
		myNet->g_listen.Listen();

		CBlockingSocket recvedSocket;
		CSockAddr recvedAddr;
		myNet->g_listen.Accept(recvedSocket, recvedAddr);


		SOCKET_INFO socket_info;
		
		//建立event關聯
		socket_info.m_hSocket = recvedSocket.GetSocket();
		socket_info.m_hEvent = WSACreateEvent();
		WSAEventSelect(socket_info.m_hSocket, socket_info.m_hEvent, FD_READ);

		int id = myNet->GetAnFreeID();

		//填寫傳給RecvThread的參數
		RECVTHREADPARAM *pParam = new RECVTHREADPARAM;
		pParam->hSocket = socket_info.m_hSocket;
		pParam->hEvent = socket_info.m_hEvent;
		pParam->ID = id;
		pParam->pNet = myNet;

		//avoid deadlock
		Slock.Lock();
        myNet->m_SocketMap[id] = socket_info;
		Slock.Unlock();
		if(myNet->m_pHandler->OnAccept(id) == -1)  //if not accept
			myNet->DisConnectInRecv(id);
		else{
			Slock.Lock();
			myNet->m_SocketMap[id].m_RecvThread =  AfxBeginThread(RecvThProc, (LPVOID)pParam); //begin recv thread		
			Slock.Unlock();
		}
	}
	return 0;
}

CNet::CNet(){
	if(InitWinSock() == -1)
		::MessageBox(0, "Can't initialize winsock! - CNet::InitWinSock()", 0, 0);


	m_Start = false;

	m_tListen = NULL;
	m_IDcounter = 0;
}

int CNet::InitWinSock(){
	WSADATA wsaData;
	int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
	if(iResult != NO_ERROR)
		return -1;
	return 0;
}

int CNet::Connect(CString* pAddr, int port){

	CBlockingSocket conn_socket;
	conn_socket.Create();
	CSockAddr sock_addr((LPCTSTR)*pAddr, port);

	if( conn_socket.Connect(sock_addr) == SOCKET_ERROR)
		return -1;

	SOCKET_INFO socket_info;
	ZeroMemory(&socket_info, sizeof(SOCKET_INFO));

	//建立event關聯

	socket_info.m_hSocket = conn_socket.GetSocket();
	socket_info.m_hEvent = WSACreateEvent();
	WSAEventSelect(socket_info.m_hSocket, socket_info.m_hEvent, FD_READ|FD_CLOSE);

	int id = GetAnFreeID();

	//fill the param, will be deleted by RecvThread
	RECVTHREADPARAM *pParam = new RECVTHREADPARAM;
	pParam->hSocket = socket_info.m_hSocket;
	pParam->hEvent = socket_info.m_hEvent;
	pParam->ID = id;
	pParam->pNet = this;
	
	CSingleLock Slock(&m_csSocketMap);
	Slock.Lock();
	m_SocketMap[id] = socket_info;
	m_SocketMap[id].m_RecvThread =  AfxBeginThread(RecvThProc, (LPVOID)pParam); //begin recv thread
	Slock.Unlock();
	Sleep(10);
	
	return id;
}


int CNet::Send(NETOBJ* pobj){
	CSingleLock Slock(&m_csSocketMap);

	if(m_SocketMap.count(pobj->m_ID) == 1){

		Slock.Lock();
		CBlockingSocket sendSocket(m_SocketMap[pobj->m_ID].m_hSocket);
		Slock.Unlock();
		//sending header
		if(sendSocket.Send((char*)&(pobj->m_header), sizeof(pobj->m_header)) == SOCKET_ERROR){
			ErrorDisConnect(pobj->m_ID);
			delete pobj;
			return -1;
		}

		//sending buf
		if(sendSocket.Send(pobj->m_pBuf, pobj->m_header.m_length) == SOCKET_ERROR){
			ErrorDisConnect(pobj->m_ID);
			delete pobj;
			return -1;
		}

		delete pobj;
		return 0;
	}
	else
		return -1;
}

int CNet::Send(NETOBJ & netobj){
	if(m_SocketMap.count(netobj.m_ID) == 1){
		CSingleLock Slock(&m_csSocketMap);
		Slock.Lock();
		CBlockingSocket sendSocket(m_SocketMap[netobj.m_ID].m_hSocket);
		Slock.Unlock();
		//sending header
		if(sendSocket.Send((char*)&netobj.m_header, sizeof(netobj.m_header)) == SOCKET_ERROR){
			ErrorDisConnect(netobj.m_ID);
			return -1;
		}

		//sending buf
		if(sendSocket.Send(netobj.m_pBuf, netobj.m_header.m_length) == SOCKET_ERROR){
			ErrorDisConnect(netobj.m_ID);
			return -1;
		}

		return 0;
	}
	else
		return -1;
}

int CNet::GetAnFreeID(){
	//if(m_SocketMap.size() == MAX_CONNECTION){
	//}
	CSingleLock Slock(&m_csSocketMap);
	m_IDcounter = (m_IDcounter + 1)%MAX_CONNECTION;
	Slock.Lock();
	while (m_SocketMap.count(m_IDcounter)){
		m_IDcounter = (m_IDcounter + 1)%MAX_CONNECTION;
	}
	Slock.Unlock();
	return m_IDcounter;
}

int CNet::Run(int port){
	if(m_Start)
		return -1;
	else{
		CSockAddr sa(INADDR_ANY, port);
		if(g_listen.Create() == -1)
			return -1;
		g_listen.Bind(sa);

		if(m_pHandler == NULL)
			return -1;
		m_Start = true;
		m_tRefresh = AfxBeginThread(RefreshThProc, (LPVOID)this);
		m_tListen = AfxBeginThread(LisThProc, (LPVOID)this);
		

		return 0;
	}
}

int CNet::DisConnect(int ID){

	//delete ID from map
	CSingleLock Slock(&m_csSocketMap);
	Slock.Lock();
	SOCKETMAP::iterator pos = m_SocketMap.find(ID);
	SOCKET_INFO socket_info = pos->second;
	m_SocketMap.erase(pos);
	Slock.Unlock();

	TerminateThread(socket_info.m_RecvThread->m_hThread, 0);
	WSACloseEvent(socket_info.m_hEvent);

	CBlockingSocket bSocket(socket_info.m_hSocket);
	bSocket.Send((char*) &disconn_header, sizeof(disconn_header));
	closesocket(socket_info.m_hSocket);
	return 0;
}

int CNet::ErrorDisConnect(int id){
	CSingleLock Slock(&m_csSocketMap);
	
	//get SOCKET_INFO
	Slock.Lock();
	if(m_SocketMap.count(id) <= 0)
		return -1;
	SOCKETMAP::iterator pos = m_SocketMap.find(id);
	SOCKET_INFO socket_info = pos->second;
	m_SocketMap.erase(pos);
	Slock.Unlock();

	TerminateThread(socket_info.m_RecvThread->m_hThread, 0);
	m_pHandler->OnClose(id);
	WSACloseEvent(socket_info.m_hEvent);
	closesocket(socket_info.m_hSocket);
	
	return 0;
}

int CNet::DisConnectInRecv(int id){
	CSingleLock Slock(&m_csSocketMap);

	//get SOCKET_INFO
	Slock.Lock();
	if(m_SocketMap.count(id) <= 0)
		return -1;
	SOCKETMAP::iterator pos = m_SocketMap.find(id);
	SOCKET_INFO socket_info = pos->second;
	m_SocketMap.erase(pos);
	Slock.Unlock();

	//need not to close Thread
	m_pHandler->OnClose(id);
	WSACloseEvent(socket_info.m_hEvent);
	closesocket(socket_info.m_hSocket);
	
	return 0;
}
	

void CNet::SetHandler(CNetHandler *phandler){
	m_pHandler = phandler;
}

int CNet::GetAddr(int id, CString* pAddr, int * pPort){
	CSingleLock Slock(&m_csSocketMap);

	//get SOCKET_INFO
	Slock.Lock();
	SOCKET_INFO socket_info = m_SocketMap[id];
	Slock.Unlock();

	CBlockingSocket bSocket(socket_info.m_hSocket);
	CSockAddr sockaddr;
	if( SOCKET_ERROR == bSocket.GetPeerAddr(sockaddr)){
		ErrorDisConnect(id);
		return -1;
	}
	*pAddr = sockaddr.DottedDecimal();
	*pPort  = sockaddr.Port();
	return 0;
}



void CNet::Stop(){
	if(m_Start){

		TerminateThread(m_tListen->m_hThread, 0);
		TerminateThread(m_tRefresh->m_hThread, 0);
		m_Start = false;

		g_listen.Close();

		SOCKETMAP::iterator pos;
		for(pos = m_SocketMap.begin(); pos != m_SocketMap.end(); ++pos){
			SOCKET_INFO socket_info = pos->second;
			TerminateThread(socket_info.m_RecvThread->m_hThread, 0);
			WSACloseEvent(socket_info.m_hEvent);

			CBlockingSocket bSocket(socket_info.m_hSocket);
			bSocket.Write((char*) &disconn_header, sizeof(disconn_header));
			closesocket(socket_info.m_hSocket);
		}

		m_SocketMap.clear();
	}

}

void CNet::Refresh(){

	CSingleLock Slock(&m_csSocketMap);
	Slock.Lock();

	SOCKETMAP::iterator pos = m_SocketMap.begin();
	while(pos != m_SocketMap.end()){
		CBlockingSocket bSocket(pos->second.m_hSocket);
		if(bSocket.Write((char*)&refresh_header, sizeof(refresh_header)) == SOCKET_ERROR){

			//disconnect
			TerminateThread(pos->second.m_RecvThread->m_hThread, 0);
			WSACloseEvent(pos->second.m_hEvent);
			bSocket.Close();
			pos = m_SocketMap.erase(pos);
			m_pHandler->OnClose(pos->first);
		}
		else{
			++pos;
		}

	}
	Slock.Unlock();

	
}

CNet::~CNet(){
	Stop();
}