// downloadPcDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Afxinet.h"
#include "downloadPc.h"
#include "debug.h"
#include "import.h"
#include "downloadPcDlg.h"
#include "ftpsetup1.h"
#include "import.h"
#include <process.h>
#include "dwusb.h"
#include "Pass.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDownloadPcDlg dialog

CDownloadPcDlg::CDownloadPcDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDownloadPcDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDownloadPcDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDownloadPcDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDownloadPcDlg)
	DDX_Control(pDX, IDC_DWSTATUS, m_ctlStatus);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDownloadPcDlg, CDialog)
	//{{AFX_MSG_MAP(CDownloadPcDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
	ON_COMMAND(ID_SETUP_FTP, OnSetupFtp)
	ON_WM_TIMER()
	ON_WM_LBUTTONDOWN()
	ON_COMMAND(ID_IMPORT_APP, OnImportApp)
	ON_COMMAND(ID_SYSTEM_NETCARDPRINTFCONSOLE, OnSystemNetcardprintfconsole)
	ON_WM_CLOSE()
	ON_COMMAND(IDOK, OnOk)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

int runTar(const char *filename, const char *dir)
{
	STARTUPINFO si;
    PROCESS_INFORMATION pi;
	char cmd[256];

	sprintf(cmd, "bin\\tar -xvf %s", filename);

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;
    ZeroMemory( &pi, sizeof(pi) );

    // Start the child process. 
    if( !CreateProcess( NULL, // No module name (use command line). 
		cmd, // Command line. 
        NULL,             // Process handle not inheritable. 
        NULL,             // Thread handle not inheritable. 
        FALSE,            // Set handle inheritance to FALSE. 
        0,                // No creation flags. 
        NULL,             // Use parent's environment block. 
        dir,              // Use abs path 
        &si,              // Pointer to STARTUPINFO structure.
        &pi )             // Pointer to PROCESS_INFORMATION structure.
    ) 
    {
        AfxMessageBox("Cannot create process to untar id file", MB_OK | MB_ICONSTOP);
		return -1;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

	return 0;
}

Cdebug *dbg = NULL;
FILE *flog = NULL;
void
dbgPrintf(char *s)
{
	if (dbg) dbg->addPrintf(s);
	if (flog) {
		fprintf(flog, "%s\n", s);
		fflush(flog);
	}

	return;
}

void 
removeAllIdFiles(char *dir)
{
	char name[128];

	for (int i=0; i<1000; i++) {
		sprintf(name, "%s\\id\\%3.3d.id", dir, i);
		remove(name);
	} 
}

FILE *
getIdFile(CDownloadPcDlg *dlg)
{
	FILE *f;
	char name[600], buf[1024];
	CString idfile;

	sprintf(name, "%s\\id\\%3.3d.id", dlg->m_current_path, dlg->m_id);
	sprintf(buf, "Status: check file %s\n", name);
	dlg->m_ctlStatus.SetWindowText(buf);

	f = fopen(name, "rb");
	if (f == NULL) {
		CInternetSession pInet("downloadPc", 1, PRE_CONFIG_INTERNET_ACCESS);
		CFtpConnection *ftp;

		sprintf(buf, "Status: connect to ftp server %s\n", dlg->m_host);
		if (dlg->m_setupFtp) return NULL;
		dlg->m_ctlStatus.SetWindowText(buf);
		try {
			ftp = pInet.GetFtpConnection(dlg->m_host, dlg->m_user, dlg->m_password, dlg->m_port, FALSE);
		} catch (CInternetException* pEx) {
			// catch errors from WinINet
			TCHAR szErr[1024];

			dlg->m_ctlStatus.SetWindowText("Status: ftp error");
			memcpy(szErr, "FTP:", 4);
			if (pEx->GetErrorMessage(szErr+4, 1020))
				AfxMessageBox(szErr, MB_OK | MB_ICONSTOP);
			else
				AfxMessageBox("Ftp cannot connect", MB_OK | MB_ICONSTOP);
			pEx->Delete();
			ftp = NULL;
		}

		if (ftp) {
			CFtpFileFind finder(ftp);

			/* XXXX for test on local machine 
			ftp->SetCurrentDirectory("aaaa"); */  

			if (finder.FindFile(_T("*"))) {
				finder.FindNextFile();
				idfile = finder.GetFileName();
				sprintf(buf, "Status: ftp get %s", idfile);
				dlg->m_ctlStatus.SetWindowText(buf);
				sprintf(buf, "%s\\%s", dlg->m_current_path, idfile); 
				if (ftp->GetFile(idfile, buf) == 0) {
					sprintf(buf, "Ftp get error code = %d", GetLastError());
					AfxMessageBox(buf , MB_OK | MB_ICONSTOP);
				} else {
					sprintf(buf, "Status: untar file %s", idfile);
					dlg->m_ctlStatus.SetWindowText(buf);
					removeAllIdFiles(dlg->m_current_path);

					if (runTar((LPCSTR) idfile, dlg->m_current_path)) {
						sprintf(buf, "Status: untar <bin\\tar xvf %s> failed", idfile);
						dlg->m_ctlStatus.SetWindowText(buf);
					} else {
						dlg->m_id = 1;
						sprintf(name, "%s\\id\\%3.3d.id", dlg->m_current_path, 1);
						AfxGetApp()->WriteProfileInt("iQue Download PC", "Current ID", 1);
						AfxGetApp()->WriteProfileInt("iQue Download PC", "ID Programmed", 0);
						sprintf(buf, "Status: untar file %s done", idfile);
						dlg->m_ctlStatus.SetWindowText(buf);

						f = fopen(name, "rb");
						if (!f) AfxMessageBox("Cannot read untar id. Please check untar files!", MB_OK | MB_ICONSTOP);

					}
					sprintf(buf, "%s\\%s", dlg->m_current_path, idfile);
					remove(buf);
				}
			} 

			finder.Close();
			ftp->Close();
			delete ftp;
			pInet.Close();
		}	
	}

	return f;
}

int
readTwoNumber(char *buf)
{
	if (buf[0] >= '0' && buf[0] <= '9' && buf[1] >= '0' && buf[1] <= '9') 
		return (buf[0] - '0') * 10 + (buf[1] - '0');

	return 0;
}

int
isVersionAfter(char *ver, char *checkdate)
{
	int vd, vm, vy;
	int d, m, y;

	vy = readTwoNumber(ver+6);
	y = readTwoNumber(checkdate + 6);
	if (vy > y) 
		return 1;
	else if (vy == y) {
		vm = readTwoNumber(ver);
		m = readTwoNumber(checkdate);
		if (vm > m) return 1;
		else if (vm == m) {
			vd = readTwoNumber(ver+3);
			d = readTwoNumber(checkdate+3);
			if (vd > d) return 1;
		}
	}

	return 0;
}

int 
ncSystemUpgrade(CDownloadPcDlg *dlg, int upgrade)
{
	char buf[1024];

	if (upgrade) {
		dlg->m_ctlStatus.SetWindowText("Status: system upgrade ...");
		if (dlg->m_boot2.GetLength() <= 0) {
			AfxMessageBox("System not setup yet", MB_OK|MB_ICONSTOP);
			return -1;
		} 
		
		sprintf(buf, "Your OS is built before %s, do you want to upgrade?", DW_OLD_VERSION); 
		if (AfxMessageBox(buf, MB_YESNO|MB_ICONSTOP) == IDNO) {
			return -2;
		}
	}

	if (dlg->m_boot1.GetLength() > 0) {
		sprintf(buf, "Status: Update boot1 with %s", dlg->m_boot1);
		dlg->m_ctlStatus.SetWindowText(buf);
		sprintf(buf, "wb 1 %s", dlg->m_boot1);
		if (shellWriteBoot(buf)) return -3;
	}

	if (dlg->m_boot2.GetLength() > 0) {
		sprintf(buf, "Status: Update boot2 with %s", dlg->m_boot2);
		dlg->m_ctlStatus.SetWindowText(buf);
		sprintf(buf, "wb 2 %s", dlg->m_boot2);
		if (shellWriteBoot(buf)) return -4;
		else if (shellVer(NULL, buf)) return -5;
	} 

	return 0;
}

int
programRtc(CDownloadPcDlg *dlg)
{
	char buf[64], rb[8];

	dlg->m_ctlStatus.SetWindowText("Status: Program RTC");
	CTime t = CTime::GetCurrentTime();
	struct tm* osTime;  
	osTime = t.GetLocalTm( NULL );

	sprintf(buf, "date %02d/%02d/%02d %02d:%02d%:%02d",
		osTime->tm_mon+1, osTime->tm_mday, osTime->tm_year-100, 
		osTime->tm_hour, osTime->tm_min, osTime->tm_sec);

	if (shellDate(buf, NULL)) {
		AfxMessageBox("Cannot program clock", MB_OK|MB_ICONSTOP);
		return -1;
	}

	if (shellDate("date", rb)) {
		AfxMessageBox("Read back clock", MB_OK|MB_ICONSTOP);
		return -1;
	}

	CTime t2 = CTime::GetCurrentTime();
	struct tm* osTime2;  
	osTime2 = t2.GetLocalTm( NULL );

	if (((rb[0] != osTime->tm_mon+1) && (rb[0] != osTime2->tm_mon+1)) ||
		((rb[1] != osTime->tm_mday) && (rb[1] != osTime2->tm_mday)) ||
		((rb[2] != osTime->tm_year-100) && (rb[2] != osTime2->tm_year-100))) {
		sprintf(buf, "set to %02d/%02d/%02d but get %02d/%02d/%02d",
					osTime->tm_mon+1, osTime->tm_mday, osTime->tm_year-100, 
					rb[0], rb[1], rb[2]);
		AfxMessageBox(buf, MB_OK|MB_ICONSTOP);
		return -3;
	}

	return 0;
}

unsigned __stdcall workThread(LPVOID lpParameter)
{
	int rv, i;
	char buf[1024], id[128], kpid[MAX_KP_LEN], name[600];
	FILE *fid=NULL, *fp;
	CDownloadPcDlg *dlg = (CDownloadPcDlg *) lpParameter;

	while (1) {
		dlg->updatePic();

		switch (dlg->m_status) {
		case DW_WAIT_CONNECT:
			dlg->m_ctlStatus.SetWindowText("Status: Please turn on GBA and connect USB to PC");
			for (; ;) {
				if (isUsbConnected()) break;
				else Sleep(1000);
			} 
			dlg->m_status = DW_NC_CHECKUP;
			break;
		case DW_NC_CHECKUP:
			dlg->m_ctlStatus.SetWindowText("Status: NC handshake");
			if (shellInit()) dlg->m_status = DW_FAIL_UNPLUG;
			dlg->m_ctlStatus.SetWindowText("Status: Check NC version version");

			if (dlg->m_status != DW_FAIL_UNPLUG) {
				if (shellVer(NULL, buf)) dlg->m_status = DW_FAIL_UNPLUG;
				else {
					if (isVersionAfter(buf, DW_OLD_VERSION)) {
						dlg->m_status = DW_STATUS_FTP;
					} else dlg->m_status = DW_NC_UPGRADE;
				}
			} 
			break;
		case DW_NC_UPGRADE:
			if (ncSystemUpgrade(dlg, 1)) dlg->m_status = DW_FAIL_UNPLUG;
			else dlg->m_status = DW_WAIT_POWERCYCLE;
			break;
		case DW_WAIT_POWERCYCLE:
			dlg->m_ctlStatus.SetWindowText("Status: wait for GBA power off ...");
			for (; ;) {
				if (isUsbConnected()) Sleep(1000);
				else break;
			} 
			dlg->m_ctlStatus.SetWindowText("Status: wait for GBA power on ...");
			for (; ;) {
				if (isUsbConnected()) break;
				else Sleep(1000);
			} 
			dlg->m_status = DW_NC_CHECKUP;
			break;
		case DW_STATUS_FTP:
			dlg->m_ctlStatus.SetWindowText("Status: try to read id file");
			if (fid) fclose(fid);
			fid = getIdFile(dlg);
			if (fid != NULL) dlg->m_status = DW_ID_CHECKUP;
			else {
				Sleep(1000); 
				break;
			}
			memset(kpid, 0, sizeof(kpid));
			memset(id, 0, sizeof(id));
			saveIds(fid, id, kpid);
			if (fid) fclose(fid);
			fid = NULL;
			break;
		case DW_ID_CHECKUP:
			dlg->m_ctlStatus.SetWindowText("Status: check kilopass ...");

			rv = checkKpProg(dlg->m_current_path, id, kpid);
			if (rv == KP_MATCH_DONE) {
				dlg->m_status = DW_DW_APPS;
			} else if (rv == KP_NOT_PROG) {
				if 	(AfxGetApp()->GetProfileInt("iQue Download PC", "ID Programmed", 0) == 1) {
					/* * * *  Adrain will give proposal here * * * */

				}
				dlg->m_status = DW_STATUS_SCAN;
			} else {
				AfxMessageBox("Kilopass checkup failed!", MB_OK | MB_ICONSTOP);
				dlg->m_status = DW_FAIL_UNPLUG;
			}
			break;
		case DW_NC_PROGID:
			sprintf(buf, "Status: barcode=%s file=id\\%3.3d.id id=%s", dlg->m_barcode, dlg->m_id, id);
			dlg->m_ctlStatus.SetWindowText(buf);
			sprintf(buf, "Start to program ID ? \n ID: %s \n FILE=%s\\id\\%3.3d.id \n barcode = %s\n", 
					id, dlg->m_current_path, dlg->m_id, dlg->m_barcode); 

			if (AfxMessageBox(buf, MB_YESNO | MB_ICONQUESTION) == IDNO) {
				dlg->m_status = DW_FAIL_UNPLUG;
			} else {
				if (ncSystemUpgrade(dlg, 0)) {
					dlg->m_status = DW_FAIL_UNPLUG;
					break;
				}
				sprintf(buf, "%s\\id\\%3.3d.id", dlg->m_current_path, dlg->m_id);
				if (shellProgId(dlg->m_barcode, buf, 1)) dlg->m_status = DW_FAIL_UNPLUG;
				else  {
					dlg->m_status = DW_WAIT_POWERCYCLE;
					AfxGetApp()->WriteProfileInt("iQue Download PC", "ID Programmed", 1);
				}
			}
			break;
		case DW_STATUS_SCAN:
			dlg->m_barcodeLen = 0;
			ResetEvent(dlg->m_scan);
			dlg->m_ctlStatus.SetWindowText("Status: wait operator to scan barcode");
			WaitForSingleObject(dlg->m_scan, INFINITE);
			sprintf(buf,"Status: barcode: %s",dlg->m_barcode);
			dlg->m_ctlStatus.SetWindowText(buf);
			dlg->m_status = DW_NC_PROGID;
			break;
		case DW_DW_APPS:
			if (programRtc(dlg)) {
				dlg->m_status = DW_FAIL_UNPLUG;
				break;
			}

			dlg->m_ctlStatus.SetWindowText("Status: Start import applications");
			if (dlg->m_app[0].GetLength() <= 0) {
				if (AfxMessageBox("Import application is not setup, continue?", MB_YESNO | MB_ICONQUESTION) == IDNO) {
					dlg->m_status = DW_FAIL_UNPLUG;
					break;
				} 
			} 
			if (AfxMessageBox("Start to load application on NC card?", MB_YESNO | MB_ICONQUESTION) == IDNO) {
				dlg->m_status = DW_FAIL_UNPLUG;
				break;
			}

			/* Write mftr cert and id.sys file */
			dlg->m_ctlStatus.SetWindowText("Status: start to write manufacture cert");
			if (dlg->m_status != DW_FAIL_UNPLUG) {
				sprintf(buf, "rm /sys/cert.sys");
				shellRm(buf);
				sprintf(buf, "rm /sys/id.sys");
				shellRm(buf);
				sprintf(buf, "rm /sys/setup.msd");
				shellRm(buf);
				sprintf(buf, "rm /media/music/demo.mp3");
				shellRm(buf);

				sprintf(buf, "put %s\\sys\\certp.sys /sys/cert.sys", dlg->m_current_path);
				if (shellPut(buf)) {
					dlg->m_status = DW_FAIL_UNPLUG;
				}
			}

			dlg->m_ctlStatus.SetWindowText("Status: start to write id file");
			if (dlg->m_status != DW_FAIL_UNPLUG) {
				sprintf(name, "%s\\sys\\id.sys", dlg->m_current_path);
				fp = fopen(name, "wb");
				if (fp == NULL) {
					AfxMessageBox("Cannot create local file sys\\id.sys", MB_OK | MB_ICONSTOP);
					dlg->m_status = DW_FAIL_UNPLUG;
				}

				fprintf(fp, "%s\n%s", id, dlg->m_barcode);
				fclose(fp);
				
				sprintf(buf, "put %s /sys/id.sys", name);
				if (shellPut(buf)) 
					dlg->m_status = DW_FAIL_UNPLUG;
			}
			dlg->m_id++;
			AfxGetApp()->WriteProfileString("iQue Download PC", "ID Programmed", 0);
 			AfxGetApp()->WriteProfileInt("iQue Download PC", "Current ID", dlg->m_id);

			if (dlg->m_status != DW_FAIL_UNPLUG) {
				for (i=0; i<MAX_APP_NUM; i++) {
					if (dlg->m_app[i].GetLength() > 0) {
						sprintf(buf, "Status:import %s", dlg->m_app[i]);
						dlg->m_ctlStatus.SetWindowText(buf);
						sprintf(buf, "import %s", dlg->m_app[i]);
						if (shellImport(buf)) {
							dlg->m_status = DW_FAIL_UNPLUG;
							break;
						}
					}
				}
			}

			/* Prepare final boot2 and iQue setup disk */
			if ((dlg->m_status != DW_FAIL_UNPLUG) && (dlg->m_fBoot2.GetLength() > 0)) {
				sprintf(buf, "Status: Update final boot2 %s", dlg->m_fBoot2);
				dlg->m_ctlStatus.SetWindowText(buf);
				sprintf(buf, "wb 2 %s", dlg->m_fBoot2);
				if (shellWriteBoot(buf)) dlg->m_status = DW_FAIL_UNPLUG;
				else {
					sprintf(buf, "Status: prepare iQue installation disk %s", dlg->m_install);
					dlg->m_ctlStatus.SetWindowText(buf);
					sprintf(buf, "put %s /sys/setup.msd", dlg->m_install);
					if (shellPut(buf)) dlg->m_status = DW_FAIL_UNPLUG;
				}
			}

			/* Prepare MP3 file for manual Audio test */
			if ((dlg->m_status != DW_FAIL_UNPLUG) && (dlg->m_mp3.GetLength() > 0)) {
				sprintf(buf, "Status: put %s for audio test", dlg->m_mp3);
				dlg->m_ctlStatus.SetWindowText(buf);
				sprintf(buf, "mkdir media");
				shellMkdir(buf);
				sprintf(buf, "mkdir /media/music");
				shellMkdir(buf);
				sprintf(buf, "put %s /media/music/demo.mp3", dlg->m_mp3);
				if (shellPut(buf)) dlg->m_status = DW_FAIL_UNPLUG;
			}

			if (dlg->m_status != DW_FAIL_UNPLUG) dlg->m_status = DW_OK_UNPLUG;

			break;
		case DW_OK_UNPLUG:
		case DW_FAIL_UNPLUG:
			for (; ;) {
				dlg->m_ctlStatus.SetWindowText("Status: wait for NC disconnect ...");
				if (isUsbConnected()) Sleep(1000);
				else break;
			} 
			dlg->m_status = DW_WAIT_CONNECT;
			break;
		}
	}

	return 0;
}

/////////////////////////////////////////////////////////////////////////////
// CDownloadPcDlg message handlers

BOOL CDownloadPcDlg::OnInitDialog()
{
	CDownloadPcApp *app = (CDownloadPcApp *) AfxGetApp();
	CDialog::OnInitDialog();
	int i;
	char buf[1024];
	
	memset(m_barcode, 0, sizeof(m_barcode));

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	GetCurrentDirectory(MAX_PATH_LEN, m_current_path);
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	if (app->GetProfileInt("iQue Download PC", "NOT_1st_TIME_VER0002", 0) == 0) {
		removeAllIdFiles(m_current_path);
		app->WriteProfileInt("iQue Download PC", "NOT_1st_TIME_VER0002", 1);
	}

	m_host = app->GetProfileString("iQue Download PC", "Host", NULL);
	m_password = app->GetProfileString("iQue Download PC", "key",  NULL);
	m_port = app->GetProfileInt("iQue Download PC", "Port", 21);
	m_user = app->GetProfileString("iQue Download PC", "User", NULL);
	m_id = app->GetProfileInt("iQue Download PC", "Current ID", 1);
	m_status = DW_WAIT_CONNECT;
	m_count = m_noftp = 0;

	/* Try to config boot2 and apps for download */
	m_boot1 = app->GetProfileString("iQue Download PC", "Boot1", NULL);
	m_boot2 = app->GetProfileString("iQue Download PC", "Boot2", NULL);
	m_fBoot2 = app->GetProfileString("iQue Download PC", "Final boot2", NULL);
	m_install = app->GetProfileString("iQue Download PC", "Install", NULL);
	m_mp3 = app->GetProfileString("iQue Download PC", "Mp3", NULL);
	for (i=0; i<MAX_APP_NUM; i++) {
		sprintf(buf, "DOWNLOAD(ver 0.1) APP0%d", i);
		m_app[i] = app->GetProfileString("iQue Download PC", buf, NULL);
	}

	m_dbg = NULL;
	m_thread = NULL;
	m_scan = NULL;
	for (i=0; i<MAX_PATH_LEN; i++) {
		if ((m_current_path[i] == ' ') || (m_current_path[i] == '\t')) {
			AfxMessageBox("Fatal error: path cannot contain blank char!", MB_OK | MB_ICONSTOP);	
			EndDialog(0);
			return FALSE;
		} else if (m_current_path[i] == 0)
			break;
	}

	sprintf(buf, "%s\\sys\\certp.sys", m_current_path);
	FILE *fp;
	fp = fopen(buf, "rb");
	if (fp == NULL) {
		AfxMessageBox("Fatal error! Please start prgram in .exe folder", MB_OK | MB_ICONSTOP);
		EndDialog(-1);
	} else fclose(fp);

	m_scan = CreateEvent(NULL, TRUE, FALSE, "DownloadPCScan");
	if (m_scan == NULL) {
		EndDialog(0);
		return FALSE;
	}

	UINT id;
	m_thread = (HANDLE) _beginthreadex(NULL, 0, &workThread, this, 0, &id);
	if (m_thread == NULL) {
		CloseHandle(m_scan);
		EndDialog(0);
		return FALSE;
	}
	
	m_timer = SetTimer(1, 200, NULL);
	m_ctlStatus.SetWindowText("Status: check id file");
	m_barcodeLen = -1;
	m_start = -1;
	m_setupFtp = 0;

	sprintf(buf, "%s\\idprog.log", m_current_path);
	flog = fopen(buf, "a+b");
	CTime t = CTime::GetCurrentTime();
	CString s = t.Format( "%#c" );
	if (flog != NULL) {
		fprintf(flog, "Program starts at %s\n", s);
		fflush(flog);
	}
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDownloadPcDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
void CDownloadPcDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CPaintDC dc(this); 
		CBitmap bm, bm2;
		CDC disp;

		switch (m_status) {
		case DW_WAIT_CONNECT:
			bm.LoadBitmap(IDB_BITMAP3);
			break;
		case DW_NC_CHECKUP:
		case DW_ID_CHECKUP:
			bm.LoadBitmap(IDB_BITMAP10);
			break;
		case DW_NC_UPGRADE:
			bm.LoadBitmap(IDB_BITMAP11);
			break;
		case DW_WAIT_POWERCYCLE:
			bm.LoadBitmap(IDB_BITMAP12);
			break;
		case DW_STATUS_FTP:
			bm.LoadBitmap(IDB_BITMAP1);
			break;
		case DW_STATUS_SCAN:
			bm.LoadBitmap(IDB_BITMAP2);
			break;
		case DW_NC_PROGID :
			bm.LoadBitmap(IDB_BITMAP9);
			break;
		case DW_DW_APPS:
			bm.LoadBitmap(IDB_BITMAP7);
			break;
		case DW_OK_UNPLUG:
			bm.LoadBitmap(IDB_BITMAP4);
			break;
		case DW_FAIL_UNPLUG:
			bm.LoadBitmap(m_count&1 ? IDB_BITMAP5 : IDB_BITMAP6);
			break;
		}
		m_oldstatus = m_status;
		disp.CreateCompatibleDC(&dc);

		disp.SelectObject(&bm);
		dc.BitBlt(40, 0, 320, 180, &disp, 0, 0, SRCCOPY);

		if (m_status == DW_DW_APPS || m_status == DW_NC_UPGRADE) {
			int x, y;
			bm2.LoadBitmap(IDB_BITMAP8);
			disp.SelectObject(&bm2);
			x = 270 - (m_count % 11) * 17;
			y = (m_count % 11);
			y = 35 + (y-5) * (y-5);
			dc.BitBlt(x, y, 15, 13, &disp, 0, 0, SRCCOPY);
		}

		CDialog::OnPaint();
	}

	if (!m_noftp) {
		m_noftp = 1;
		if (m_host.GetLength()<=0) OnSetupFtp();
		if (m_app[0].GetLength() <= 0) OnImportApp();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDownloadPcDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDownloadPcDlg::OnAppAbout() 
{
	// TODO: Add your command handler code here
	CAboutDlg dlg;

	dlg.DoModal();
}

void CDownloadPcDlg::OnSetupFtp() 
{
	// TODO: Add your command handler code here
	CFtpSetup dlg;
	CPass     passDlg;
	CDownloadPcApp *app = (CDownloadPcApp *) AfxGetApp();

	m_setupFtp = 1;
	if (passDlg.DoModal() == IDOK) {
		if (passDlg.m_pass != "1028") {
			MessageBox("Invalid password", "Password", MB_OK | MB_ICONSTOP);
			goto out;
		}
	} else goto out;

	dlg.m_host = m_host;
	dlg.m_port = m_port;
	dlg.m_user = m_user;
	dlg.m_password = m_password;
	
	if (dlg.DoModal() == IDOK) {
		m_host = dlg.m_host;
		m_port = dlg.m_port;
		m_user = dlg.m_user;
		m_password = dlg.m_password;

		app->WriteProfileString("iQue Download PC", "Host", m_host);
	    app->WriteProfileString("iQue Download PC", "key",  m_password);
	    app->WriteProfileInt("iQue Download PC", "Port", m_port);
	    app->WriteProfileString("iQue Download PC", "User", m_user);
	}
out:
	m_setupFtp = 0;

	return;

}	

void CDownloadPcDlg::updatePic() 
{
	
	CRect rect;

	if ((m_status != m_oldstatus) || 
		(m_status == DW_DW_APPS) ||
		(m_status == DW_NC_UPGRADE) ||
		(m_status == DW_FAIL_UNPLUG)) {
		GetClientRect(&rect);
		InvalidateRect(&rect, FALSE);
		if (m_status != m_oldstatus) m_count = 0;
	}
	
}

void CDownloadPcDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	m_count++;
	updatePic();
	
	CDialog::OnTimer(nIDEvent); 
}

BOOL CDownloadPcDlg::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
	if (pMsg->message == WM_KEYDOWN && m_status == DW_STATUS_SCAN) {
		if (m_barcodeLen >= 0) {
			if (pMsg->wParam == '\r' || pMsg->wParam == '\n') {
				if (m_barcodeLen != 11) {
					MessageBox("Invalid barcode(should be 11 letters or numbers)", "Barcode", MB_OK | MB_ICONEXCLAMATION);
					m_barcodeLen = 0;	
					return true;
				}
				m_barcode[m_barcodeLen] = 0;
				m_barcodeLen = 0;
				SetEvent(m_scan);
				return TRUE;
			} else if (pMsg->wParam >= 0x20) m_barcode[m_barcodeLen++] = (char) pMsg->wParam;
		}
	}

	if (pMsg->wParam == 27 || pMsg->wParam==10 || pMsg->wParam==13) 
		return TRUE;   

	return CDialog::PreTranslateMessage(pMsg);
}

void CDownloadPcDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
#if XXXXXXX
	if (m_status == DW_STATUS_START && m_start == 0) {
		if (point.x >=40 && point.x < 200 && point.y >0 && point.y<180) 
			m_start = -1;

		if (point.x >=200 && point.x < 360 && point.y >0 && point.y<180)
			m_start = 1;

		if (m_start) SetEvent(m_scan);
	}
#endif

	CDialog::OnLButtonDown(nFlags, point);
}

void CDownloadPcDlg::OnImportApp() 
{
	// TODO: Add your command handler code here
	CImport dlg;
	int i;
	char buf[128];
	CPass     passDlg;
	CDownloadPcApp *app = (CDownloadPcApp *) AfxGetApp();

	if (passDlg.DoModal() == IDOK) {
		if (passDlg.m_pass != "1028") {
			MessageBox("Invalid password", "Password", MB_OK | MB_ICONSTOP);
			return;
		}
	} else return;
	
	dlg.m_boot2 = m_boot2;
	dlg.m_boot1 = m_boot1;
	for (i=0; i<MAX_APP_NUM; i++) 
		dlg.m_app[i] = m_app[i];
	dlg.m_fBoot2 = m_fBoot2;
	dlg.m_install = m_install;
	dlg.m_mp3 = m_mp3;

	if (dlg.DoModal() == IDOK) {
		for (i=0; i<MAX_APP_NUM; i++) 
			m_app[i] = dlg.m_app[i];
		m_boot2 = dlg.m_boot2;
		m_boot1 = dlg.m_boot1;
		m_install = dlg.m_install;
		m_fBoot2 = dlg.m_fBoot2;
		m_mp3 = dlg.m_mp3;
	
		app->WriteProfileString("iQue Download PC", "Boot2", m_boot2);
		app->WriteProfileString("iQue Download PC", "Boot1", m_boot1);
		app->WriteProfileString("iQue Download PC", "Final boot2", m_fBoot2);
		app->WriteProfileString("iQue Download PC", "Install", m_install);
		app->WriteProfileString("iQue Download PC", "Mp3", m_mp3);
		for (i=0; i<MAX_APP_NUM; i++) {
			sprintf(buf, "DOWNLOAD(ver 0.1) APP0%d", i);
			app->WriteProfileString("iQue Download PC", buf, m_app[i]);
		}
	}
}

void CDownloadPcDlg::OnSystemNetcardprintfconsole() 
{
	// TODO: Add your command handler code here
	if (m_dbg != NULL) {
		if (m_dbg->GetSafeHwnd()) {
			m_dbg->ShowWindow(1);
			return;
		}
	} else m_dbg = new Cdebug();

	m_dbg->Create(IDD_PTF_WND);
    m_dbg->ShowWindow(1);

	dbg = m_dbg;
}

CDownloadPcDlg::~CDownloadPcDlg()
{
	if (m_dbg) delete m_dbg;
	if (flog) fclose(flog);

	m_dbg = NULL;
	flog = NULL;
}

void CDownloadPcDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	if (m_thread) {
		TerminateThread(m_thread, -1);
		CloseHandle(m_thread);
	}
	m_thread = NULL;
	if (m_timer) KillTimer(m_timer);
	if (m_scan) CloseHandle(m_scan);
	if (m_dbg) delete m_dbg;
	if (flog) fclose(flog);
	flog = NULL;
	m_dbg = NULL;
	m_scan = NULL;
	m_timer = 0;
	CDialog::OnClose();
}

void CDownloadPcDlg::OnOk() 
{
	// TODO: Add your command handler code here
	if (m_thread) {
		TerminateThread(m_thread, -1);
		CloseHandle(m_thread);
	}
	m_thread = NULL;
	if (m_timer) KillTimer(m_timer);
	if (m_scan) CloseHandle(m_scan);
	if (m_dbg) delete m_dbg;
	if (flog) fclose(flog);
	flog = NULL;
	m_dbg = NULL;
	m_scan = NULL;
	m_timer = 0;
	CDialog::OnOK();
}
