// RYLLogin.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "RYLLogin.h"
#include "RYLLoginDlg.h"

#include "DlgRegionSelect.h"
#include "SimpleHTTPFile.h"


#if defined(_NATION_KR_) && !defined(_DEBUG)
#include "MyFirewall.h"
#pragma comment( lib, "MyFireWallMT.lib" )
#endif


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CRYLLoginApp

BEGIN_MESSAGE_MAP(CRYLLoginApp, CWinApp)
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()


// CRYLLoginApp construction

CRYLLoginApp::CRYLLoginApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance

	m_hDefaultResource = NULL;
	m_hDLLResource = NULL;
}


// The one and only CRYLLoginApp object

CRYLLoginApp theApp;


void SetDefaultResource()
{
	theApp.SetDefaultResource();
}

void SetDllResource()
{
	theApp.SetDllResource();
}


BOOL CreateReg(HKEY hReg)
{
	TCHAR strPath[MAX_PATH], strTemp[MAX_PATH];
	
	GetModuleFileName(NULL, strPath, sizeof(strPath));

	TCHAR* pLastToken = NULL;
	pLastToken = strrchr( strPath, '\\' );
	if( NULL == pLastToken )
	{
		pLastToken = strrchr( strPath, '/' );
		if( NULL == pLastToken )
		{
			return FALSE;
		}
	}

	int nPathLen = pLastToken - strPath;
	strncpy( strTemp, strPath, nPathLen );
	strTemp[nPathLen] = '\0';

	long lResult;
	lResult = RegSetValueEx(hReg, STR_CLIENT_REGISTRY_VALUE_NAME, 0, REG_SZ, (LPBYTE)strTemp, (unsigned long)strlen(strTemp));

	if(ERROR_SUCCESS != lResult)
	{
		wsprintf( strTemp, "Error %d", lResult );
		AfxMessageBox( strTemp );
		return FALSE;
	}
	
	return TRUE;
}


// CRYLLoginApp initialization

//#include "../GlobalScript/Network/clientsocket/LoginSocket.h"


BOOL CRYLLoginApp::InitInstance()
{
	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

// 중국 iKeeper 관련 테스트코드
//	HWND hWndTmp = CreateWindow("button", "뷁", WS_OVERLAPPEDWINDOW,
//		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, NULL, NULL);
//	ShowWindow( hWndTmp, SW_SHOW );
//	UpdateWindow( hWndTmp );
//
//
//	LoginSocket* pLoginSocket = new LoginSocket( hWndTmp );
//	pLoginSocket->ConnectToLoginServer( "61.152.255.22" );

	InitCommonControls();

	CWinApp::InitInstance();

	AfxEnableControlContainer();


#if defined(_NATION_KR_) && !defined(_DEBUG)
	myfirewall::On();
#endif

	INT_PTR nResponse;
	CRYLLoginDlg* pDlg;
	int nLoginServerDomainIndex = -1;

	m_hDefaultResource =  AfxGetResourceHandle();
	m_hDLLResource = LoadLibrary( "LoginRes.dll" );

#if defined( _NATION_CN_ )

	// 레지스트리 미존재시 생성 코드
	char szTmp[300];
	HKEY hMPClientReg;
	long lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, STR_CLIENT_REGISTRY_SUBKEY, 0, KEY_READ, &hMPClientReg);
	
	if (ERROR_SUCCESS != lResult)
	{
		if(ERROR_FILE_NOT_FOUND == lResult)
		{
			unsigned long dwDisp = 0;
			lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, STR_CLIENT_REGISTRY_SUBKEY, 0, NULL, 
                REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hMPClientReg, &dwDisp);
		
            if(ERROR_SUCCESS != lResult)
			{
				wsprintf( szTmp, "Error %d", lResult );
				AfxMessageBox( szTmp );
				return FALSE;
			}
			
			if(FALSE == CreateReg(hMPClientReg))
			{
				RegCloseKey(hMPClientReg);
				return FALSE;
			}
		} 
        else
		{
			wsprintf( szTmp, "Error %d", lResult );
			AfxMessageBox( szTmp );
			return FALSE;
		}
	}

	RegCloseKey(hMPClientReg);

#endif


#if defined( _NATION_CN_ )

	// 중국 지역런처 선택 다이얼로그 코드
	char szLauncherPath[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, szLauncherPath);
    szLauncherPath[MAX_PATH - 1] = 0;

	CString strRegionListFile(szLauncherPath);
	strRegionListFile.Append("\\locallist.dat");

	CSimpleHTTPFile httpFile;
	
    if (!httpFile.Init()) 
    {
        return false;
    }

    bool bSucceeded = false;

    while (!bSucceeded)
    {
        DeleteFile(strRegionListFile);
        httpFile.TransferFile(STR_REGION_LIST_URL, strRegionListFile);
	    	        	
	    HANDLE hFile = CreateFile(strRegionListFile,
		    GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
	
        if (INVALID_HANDLE_VALUE == hFile)
	    {
		    if (IDNO == AfxMessageBox("Failed to get Region List. Try Again ?", MB_YESNO))
		    {
			    return false;
		    }
	    }
	    else
	    {
		    CloseHandle(hFile);
            bSucceeded = true;
	    }
    }

    httpFile.Close();
	
	CDlgRegionSelect* pDlgRegionSelect = new CDlgRegionSelect;

	ParseRegionList(pDlgRegionSelect, strRegionListFile);
	DeleteFile(strRegionListFile);

	// region selection dialog
	nResponse = pDlgRegionSelect->DoModal();
	nLoginServerDomainIndex = pDlgRegionSelect->m_nRegionIndex;

	delete pDlgRegionSelect;

	if( nLoginServerDomainIndex >= m_vecDomainName.size() )
	{
		AfxMessageBox( "Error in Region List", MB_OK );
		nResponse = IDCANCEL;
	}

	if (IDCANCEL == nResponse)
	{
        SetDefaultResource();
	    FreeLibrary( m_hDLLResource );
        return false;
	}

#endif // defined( _NATION_CN_ )

	pDlg = new CRYLLoginDlg;
	m_pMainWnd = pDlg;
	
    pDlg->SetDefaultLoginServerAddress( 
        (nLoginServerDomainIndex < 0 || m_vecDomainName.size() < static_cast<size_t>(nLoginServerDomainIndex))
        ? STR_LOGIN_SERVER_ADDR
        : m_vecDomainName[nLoginServerDomainIndex]);
 
	nResponse = pDlg->DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	delete pDlg;

#if defined(_NATION_KR_) && !defined(_DEBUG)
	myfirewall::Off();
#endif

	SetDefaultResource();
	FreeLibrary( m_hDLLResource );

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}


void CRYLLoginApp::ParseRegionList(CDlgRegionSelect* pDlgRegionSelect, const char* szFileName)
{
	FILE* fp = fopen(szFileName, "rt");

	if (0 != fp)
	{
        const int MAX_DATALEN = 300;

	    char szTmp[MAX_DATALEN];
	    char szRegionName[MAX_DATALEN], szDomainName[MAX_DATALEN];

	    while(0 != fgets(szTmp, MAX_DATALEN, fp))
	    {
            szTmp[MAX_DATALEN - 1] = 0;

		    sscanf(szTmp, "%s\t%s", szRegionName, szDomainName);

		    m_vecDomainName.push_back(CString(szDomainName));		    
		    pDlgRegionSelect->m_vec_strRegionName.push_back(CString(szRegionName));
	    }

	    fclose(fp);
    }
}