#include "stdafx.h"
#include "GMTool.h"
#include "resource.h"

#include "Protocol_Cheat.h"
#include "Cheat_Common.h"
#include "NoticeMsgPlane.h"
#include <mbctype.h>

/// 공지관련
void cGMTool::InitDlgNotice()
{
	HWND hWnd = mSubDlg[GMTOOL_SUBDLG_NOTICE];

	SetDlgItemText( hWnd, IDC_RICHEDIT_TEXT, _T("") );
	SendMessage( GetDlgItem(hWnd, IDC_COMBO_NOTICETYPE), CB_SETCURSEL, 0, 0 );

	/// 리치에디트 제한 걸기
	SendDlgItemMessage( hWnd, IDC_RICHEDIT_TEXT, EM_SETLIMITTEXT, (WPARAM)NOTICEMSG_TEXT_LENGTH-1, 0 );

	/// 위치세팅
	RECT rc0;
	::GetWindowRect( mMainDlg, &rc0 );
	int x = rc0.right;
	int y = rc0.top + GetSystemMetrics(SM_CYCAPTION);
	::SetWindowPos( hWnd, 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );

	mSubDlgPos[GMTOOL_SUBDLG_NOTICE].x = 0;
	mSubDlgPos[GMTOOL_SUBDLG_NOTICE].y = GetSystemMetrics(SM_CYCAPTION);

	SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_PATH, mCurrentPath );
	
	if( mIsfileOpen == true )
	{
		mNoticeFileLoader.Close();
		mIsfileOpen = false;
	}
	
	TCHAR time[10];
	_itow( mTimeInterval, time, 10 );
	SetDlgItemText( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_TIME_INTERVAL, time );
	SetDlgItemText( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_FILEREAD_END, _T("") );
	SendDlgItemMessage(mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_LIST_NOTICE_FILELIST, LB_RESETCONTENT, NULL, NULL);
	KillTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1);

}

void cGMTool::OnCommandNotice( int id, int msg )
{
	switch( id )
	{
	case IDC_BUTTON_NOTICE_CANCEL:
		::ShowWindow( mSubDlg[GMTOOL_SUBDLG_NOTICE], SW_HIDE );
		if( mIsfileOpen == true )
		{
			mNoticeFileLoader.Close();
			mIsfileOpen = false;
			SetDlgItemText( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_FILEREAD_END, _T("") );
			SendDlgItemMessage(mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_LIST_NOTICE_FILELIST, LB_RESETCONTENT, NULL, NULL);
			KillTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1);
		}
		::SetActiveWindow( mParentWnd );

		break;
	case IDC_BUTTON_NOTICESEND:		/// 공지 전송
		if( NETWORK->IsConnected() == true )
		{
			HWND hComDlg = GetDlgItem( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_COMBO_NOTICETYPE );
			int i = SendMessage( hComDlg, CB_GETCURSEL, 0, 0 );
			
			/// 내용 받기
			TCHAR str[NOTICEMSG_TEXT_LENGTH] = {0,};
			int retcode = GetDlgItemTextW( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_RICHEDIT_TEXT, str, NOTICEMSG_TEXT_LENGTH );
			if( retcode == false )
				return;

			cStringT temp = str;
			temp.Replace( _T("\r\n"), _T("\0") );
			temp.Replace( _T("\t"), _T(" ") );
			temp.Replace( _T("\n"), _T("\0") );
			temp.Replace( _T("\r"), _T("\0") );

			/// 서버공지
			if( i == 0 )
			{
				MSG_REQ_CHEAT_NOTICE_SERVER msg;
				::memset( &msg, 0, sizeof( msg ) );

				msg.Category = NM_CHEAT;
				msg.Protocol = NM_CHEAT_NOTICE_SERVER_REQ;
				::Sstrncpy( msg.mMessage, MAX_CHAT_BUFFER_SIZE, temp.Cstr(), NOTICEMSG_TEXT_LENGTH );
				NETWORK->SendNetworkMsg( (char*)&msg, (unsigned short)msg.GetMsgLength() );
				
			}
			/// 채널공지
			else if( i == 1 )
			{
				MSG_REQ_CHEAT_NOTICE_CHANNEL msg;
				::memset( &msg, 0, sizeof( msg ) );

				msg.Category = NM_CHEAT;
				msg.Protocol = NM_CHEAT_NOTICE_CHANNEL_REQ;
				::Sstrncpy( msg.mMessage, MAX_CHAT_BUFFER_SIZE, temp.Cstr(), NOTICEMSG_TEXT_LENGTH );
				NETWORK->SendNetworkMsg( (char*)&msg, (unsigned short)msg.GetMsgLength() );
			}
			/// 맵 공지
			else if( i == 2 )
			{
				MSG_REQ_CHEAT_NOTICE_AREA msg;
				::memset( &msg, 0, sizeof( msg ) );

				msg.Category = NM_CHEAT;
				msg.Protocol = NM_CHEAT_NOTICE_AREA_REQ;
				::Sstrncpy( msg.mMessage, MAX_CHAT_BUFFER_SIZE, temp.Cstr(), NOTICEMSG_TEXT_LENGTH );
				NETWORK->SendNetworkMsg( (char*)&msg, (unsigned short)msg.GetMsgLength() );
			}
			else
			{
				assert(0);
				return;
			}
	
			/// 초기화
			SetDlgItemText( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_RICHEDIT_TEXT, _T("") );
		}
		break;
	case IDC_BUTTON_NOTICE_FILESEARCH:
		{

			char findPath[ MAX_PATH ];
			sprintf( findPath, "%s\\*.txt", mCurrentPath );

			DlgDirListA( mSubDlg[GMTOOL_SUBDLG_NOTICE], findPath, IDC_LIST_NOTICE_FILELIST, 0, (DDL_ARCHIVE | DDL_DRIVES | DDL_DIRECTORY | DDL_READWRITE ) );
		}
		break;

	case IDC_BUTTON_NOTICE_AUTORUN:
		{
			if( mIsfileOpen == false )
			{
				SetDlgItemTextEx( GMTOOL_SUBDLG_NOTICE, IDC_EDIT_NOTICE_FILEREAD_END, IDS_GMTOOL_NOTICE_ERROR_FILE_OPEN_FIRST );
				return;
			}
			
			SendMessage( mSubDlg[GMTOOL_SUBDLG_NOTICE], WM_COMMAND, IDC_BUTTON_NOTICESEND, BN_CLICKED );
			
			char msg [ NOTICEMSG_TEXT_LENGTH*2 ] = "";

			/// 줄과 줄 사이가 빈칸 skip
			do 
			{
				if( mNoticeFileLoader.IsEnd() == true )
				{
					mNoticeFileLoader.Close();
					mIsfileOpen = false;
					SetDlgItemTextEx( GMTOOL_SUBDLG_NOTICE, IDC_EDIT_NOTICE_FILEREAD_END, IDS_GMTOOL_NOTICE_ERROR_FILE_READ_END );
					KillTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1);
					return;
				}

				bool readtext = GetText( msg, NOTICEMSG_TEXT_LENGTH-1 );
				if ( readtext == false )
					return;

			} while( strlen( msg ) < 2 );


			SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_RICHEDIT_TEXT, msg );

			/// 타이머 설정
			BOOL retcode = FALSE;
			int time = GetDlgItemInt( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_TIME_INTERVAL, &retcode, false );
			if( retcode == FALSE )
				return;

			mTimeInterval = time;
			
			SetTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1, mTimeInterval, NULL );

		}
		break;
	case IDC_LIST_NOTICE_FILELIST:
		{
			switch( msg )
			{
				case LBN_DBLCLK:
					{
						BOOL dir;
						char selectedName[MAX_PATH];
						char path[MAX_PATH];

						dir = DlgDirSelectExA( mSubDlg[GMTOOL_SUBDLG_NOTICE], selectedName, MAX_PATH, IDC_LIST_NOTICE_FILELIST );
						
						///폴더 선택
						if( dir )
						{
							if(lstrcmpA(selectedName, "..\\") == 0)
							{
								char *p;
								p = strrchr( mCurrentPath, '\\' );
								*p = 0;
							}
							else if( selectedName[1] == ':' )
							{
								sprintf( mCurrentPath, "%c:\\", selectedName[0] );
							}
							else
							{
								sprintf( path, "%s\\%s", mCurrentPath, selectedName );
								path[::lstrlenA(path)-1]=0;
								::lstrcpyA(mCurrentPath, path );
							}
							sprintf( path, "%s\\*.txt", mCurrentPath );
							
							/// 비어있는 드라이브로 이동할 경우 DDL_DRIVES 옵션이 DDL_EXECLUSIVE를 호출하여 리스트가 생성되지 않으므로 2번 호출
							DlgDirListA( mSubDlg[GMTOOL_SUBDLG_NOTICE], path, IDC_LIST_NOTICE_FILELIST, 0, ( DDL_DRIVES ) );
							DlgDirListA( mSubDlg[GMTOOL_SUBDLG_NOTICE], path, IDC_LIST_NOTICE_FILELIST, 0, ( DDL_ARCHIVE | DDL_DRIVES | DDL_DIRECTORY | DDL_READWRITE ) );
							
							SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_PATH, mCurrentPath );
						}
						else
						{

							if( mIsfileOpen == true )
							{
								if ( mNoticeFileLoader.Close() == -1 )
								{
									SetDlgItemTextEx( GMTOOL_SUBDLG_NOTICE, IDC_RICHEDIT_TEXT, IDS_GMTOOL_NOTICE_ERROR_FILE_OPEN );
									break;
								}
							}
							
							SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_EDIT_NOTICE_FILEREAD_END, "" );

							/// 파일 입력시 .txt파일을 읽어오기
							sprintf( path, "%s\\%s", mCurrentPath, selectedName );
							
							//mNoticeFileLoader.Close();
							if( mNoticeFileLoader.Open( path, true ) == false )
								break;

							mIsfileOpen = true;

							char noticeMsg [ NOTICEMSG_TEXT_LENGTH*2 ] = "";
							
							/// 줄과 줄 사이가 빈칸 skip
							do 
							{
								if( mNoticeFileLoader.IsEnd() == true )
								{
									mNoticeFileLoader.Close();
									mIsfileOpen = false;
									SetDlgItemTextEx( GMTOOL_SUBDLG_NOTICE, IDC_EDIT_NOTICE_FILEREAD_END, IDS_GMTOOL_NOTICE_ERROR_FILE_READ_END );
									KillTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1);
									return;
								}

								bool readtext = GetText( noticeMsg, NOTICEMSG_TEXT_LENGTH-1 );
								if ( readtext == false )
									return;

							} while( strlen( noticeMsg ) < 1 );

							SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_RICHEDIT_TEXT, noticeMsg );
						}

					}
				break;
			}
		}
		break;
	}
}


void cGMTool::OnTimer()
{

	SendMessage( mSubDlg[GMTOOL_SUBDLG_NOTICE], WM_COMMAND, IDC_BUTTON_NOTICESEND, BN_CLICKED );

	char msg [ NOTICEMSG_TEXT_LENGTH*2 ] = "";
	
	/// 줄과 줄 사이가 빈칸 skip
	do 
	{
		if( mNoticeFileLoader.IsEnd() == true )
		{
			mNoticeFileLoader.Close();
			mIsfileOpen = false;
			SetDlgItemTextEx( GMTOOL_SUBDLG_NOTICE, IDC_EDIT_NOTICE_FILEREAD_END, IDS_GMTOOL_NOTICE_ERROR_FILE_READ_END );
			KillTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1);
			return;
		}

		bool readtext = GetText( msg, NOTICEMSG_TEXT_LENGTH-1 );
		if ( readtext == false )
			return;

	} while( strlen( msg ) < 1 );
	
	
	SetDlgItemTextA( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_RICHEDIT_TEXT, msg );

	SetTimer( mSubDlg[GMTOOL_SUBDLG_NOTICE], 1, mTimeInterval, NULL );

}

bool cGMTool::LoadNoticeData()
{
	HWND typeCombo = GetDlgItem( mSubDlg[GMTOOL_SUBDLG_NOTICE], IDC_COMBO_NOTICETYPE );
	if( ::IsWindow( typeCombo ) == false )
	{
		assert(0);
		return false;
	}

	/// 정보 삽입
	SendMessage( typeCombo, CB_ADDSTRING, 0, (LPARAM)_T("Server"));
	SendMessage( typeCombo, CB_ADDSTRING, 0, (LPARAM)_T("Channel"));
	SendMessage( typeCombo, CB_ADDSTRING, 0, (LPARAM)_T("Map"));
	return true;
}

bool cGMTool::GetText( char* buffer, int textLen )
{
	/// 읽어들인 바이트 
	int  readByte = 0;
	/// 읽어들인 문자 수
	int  readChar = 0;
	char readBuf[2] = "";
	int  idx = 0;

	if( mIsfileOpen == false )
		return false;

	
	do {
		
		readByte = mNoticeFileLoader.ReadLine( readBuf, 2 );

		if( readByte == 0 )
			break;

		if( readBuf[0] == '\r' || readBuf[0] == '\r\n' || readBuf[0] == '\n' )
			readBuf[0] = 0;
        
		/// 조합의 첫글자가 판단
		if( _ismbslead( (unsigned char*)readBuf, (unsigned char*)readBuf ) == -1 )
		{
			/// 읽어들인 부분의 마지막 글자가 짤려서 읽힌경우 1byte 더 읽음
			*(buffer+idx) = readBuf[0];
			++idx;
			
			mNoticeFileLoader.ReadLine( readBuf, 2 );
			*(buffer+idx) = readBuf[0];
			++idx;
			
			++readChar;
		}
		else
		{
			*(buffer+idx) = readBuf[0];
			++idx;
			++readChar;
		}

	   } while ( readByte > 0 && readChar < textLen );


// 	pFilter = strchr( buffer, '\t' );
// 	if( pFilter != NULL )
// 		*pFilter = 32;

	return true;

}