// MainPage.cpp : implementation file
//

#include "stdafx.h"
#include "dloader.h"
#include "MainPage.h"
#include "SettingsSheet.h"
#include "EdtBtnCtrl.h"
#include "BinPack.h"
#include "DlgPacketSetting.h"
#include "MainFrm.h"
#include "Calibration.h"
#include "Calibration_Struct.h"

#include <algorithm>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


#define ALL_PORT _T("All")

// Serial ports section
static _TCHAR g_sz_SP[]			= _T("Serial port");
static _TCHAR g_sz_BR[]			= _T("Baud rate");
static _TCHAR g_sz_PORT[]		= _T("Port");




// Download files section
static _TCHAR g_sz_SEC_DF[]		= _T("Download Files");

// GUI main page
static _TCHAR g_sz_SEC_GUI[]	= _T("GUI");
static _TCHAR g_sz_KEY_SEL[]	= _T("CanSelect");
static _TCHAR g_sz_KEY_EDT[]	= _T("CanEdit");
static _TCHAR g_sz_KEY_BRS[]	= _T("BaudRates");
static _TCHAR g_sz_BR_DEFAULT[]	= _T("57600,115200,230400,460800,921600");


static _TCHAR g_sz_SEC_NV[]		= _T("NV");
static _TCHAR g_sz_KEY_LNII[]   = _T("LangNVItemID");

static _TCHAR g_szUA[]            = _T("OmadmFota");
static _TCHAR g_szEDU[]           = _T("EraseDU");
static _TCHAR g_szPreload[]       = _T("Preload");
static _TCHAR g_szKernelImg2[]    = _T("KernelImg2");
static _TCHAR g_szRomDisk[]		  = _T("RomDisk");

static _TCHAR g_sz_SEC_CHIPDSPMAP[]	 = _T("ChipDspMap");
static _TCHAR g_sz_KEY_CDME[]		 = _T("enable");


#define CMD_PAC_EXIT \
	{\
		if(g_theApp.m_bCMDPackage)\
		{\
			GetParent()->PostMessage(WM_COMMAND, IDCANCEL);\
			AfxGetMainWnd()->PostMessage(WM_CLOSE);\
		}\
	}

/////////////////////////////////////////////////////////////////////////////
// CMainPage property page

IMPLEMENT_DYNCREATE(CMainPage, CPropertyPage)

CMainPage::CMainPage() : CPropertyPage(CMainPage::IDD)
{
	//{{AFX_DATA_INIT(CMainPage)
	m_bAllFiles = FALSE;
	//}}AFX_DATA_INIT
	m_pXmlConfigParse = NULL;
	m_bInit = FALSE;
	m_strIniFile = _T("");
	m_pCurProductInfo = NULL;
	m_bListInsertItemComlpete = TRUE;
	m_nBaudRate = -1;
	m_nComPort = -1;
	m_nCurProduct = -1;

	m_strCurProduct = _T("");

	m_nTmpProduct = -1;
	m_pTmpProductInfo = NULL;
	m_strTempProduct = _T("");
	

	m_nProductCount = 0;

	m_pCaliPage = NULL;
	m_pNandPage = NULL;
	m_pMultiLangPage = NULL;

	m_aFileID.RemoveAll();
	m_aFileSize.RemoveAll();
	m_strPrdVersion = _T("");
	m_mapPrdCfg.RemoveAll();

	m_wLangNVItemID = NV_MULTI_LANG_ID;

#ifdef _SPUPGRADE
	m_bCanEdit = FALSE;
	m_bCanSel = FALSE;
#else
	m_bCanEdit = TRUE;
	m_bCanSel = TRUE;
#endif

#ifdef _DOWNLOAD_FOR_PRODUCTION
	m_bCanEdit = FALSE;
	m_bCanSel = FALSE;
#endif


	m_bOmaDM = TRUE;
	m_bTmpOmaDM = TRUE;

	m_bPreload = TRUE;
	m_bTmpPreload = TRUE;

	m_bKernelImg2 = TRUE;
	m_bTmpKernelImg2 = TRUE;

	m_bRomDisk = TRUE;
	m_bTmpRomDisk = TRUE;

	m_bEnableChipDspMap = FALSE;
}

CMainPage::~CMainPage()
{
	if(m_pXmlConfigParse != NULL)
	{
		m_pXmlConfigParse->Release();
		m_pXmlConfigParse = NULL;
	}
	m_pCurProductInfo = NULL;
	m_pTmpProductInfo = NULL;	
	ClearProdInfoVector();
	m_arrAllFileName.RemoveAll();
	m_arrFileName.RemoveAll();
	m_arrProductName.RemoveAll();
	m_aFileID.RemoveAll();
	m_aFileSize.RemoveAll();
}

void CMainPage::DoDataExchange(CDataExchange* pDX)
{
	CPropertyPage::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMainPage)
	DDX_Control(pDX, IDC_EDT_PRD_VERSION, m_edtPrdVersion);
	DDX_Control(pDX, IDC_STC_PROD_COMMENT, m_stcProdComment);
	DDX_Control(pDX, IDC_LST_PRODUCT_INFO, m_lstProductInfo);
	DDX_Control(pDX, IDC_CMB_PRODUCT, m_cmbProduct);
	DDX_Control(pDX, IDC_CMB_PORT, m_cmbPort);
	DDX_Control(pDX, IDC_CMB_BAUDRATE, m_cmbBaudrate);
	DDX_Check(pDX, IDC_CHK_ALL, m_bAllFiles);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CMainPage, CPropertyPage)
	//{{AFX_MSG_MAP(CMainPage)
	ON_CBN_SELCHANGE(IDC_CMB_PRODUCT, OnSelchangeCmbProduct)
	ON_BN_CLICKED(IDC_CHK_ALL, OnChkAll)
	ON_NOTIFY(NM_DBLCLK, IDC_LST_PRODUCT_INFO, OnDblclkLstProductInfo)
	ON_NOTIFY(LVN_ENDLABELEDIT, IDC_LST_PRODUCT_INFO, OnEndlabeleditLstProductInfo)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LST_PRODUCT_INFO, OnItemchangedLstProductInfo)
	ON_WM_CTLCOLOR()
	ON_NOTIFY(NM_RCLICK, IDC_LST_PRODUCT_INFO, OnRclickLstProductInfo)
	ON_NOTIFY(NM_CLICK, IDC_LST_PRODUCT_INFO, OnClickLstProductInfo)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMainPage message handlers

BOOL CMainPage::OnInitDialog() 
{
	CPropertyPage::OnInitDialog();
	
	// TODO: Add extra initialization here
	int i = 0;
//Load Baudrate default
	m_arrBaudRateDefault.RemoveAll();
	CString strBaudRate;
	VERIFY( strBaudRate.LoadString(IDS_BAUDRATE_DEFAULT));
	int     nLen   = strBaudRate.GetLength();
	LPTSTR  lpBuf  = strBaudRate.GetBuffer(nLen);
	LPTSTR  lpFind = _tcschr(lpBuf, _T(','));
	while(lpFind != NULL)
	{
		*lpFind = _T('\0');

		m_arrBaudRateDefault.Add(lpBuf);
		lpBuf = lpFind + 1;
		lpFind = _tcschr(lpBuf, _T(','));
	}
	m_arrBaudRateDefault.Add(lpBuf);
	strBaudRate.ReleaseBuffer();

	CStringArray arrBaudRate;

	if(m_arrBaudRateConfig.GetSize()>0)
	{
		arrBaudRate.Copy(m_arrBaudRateConfig);
	}
	else
	{
		arrBaudRate.Copy(m_arrBaudRateDefault);
	}
    for(i=0;i<arrBaudRate.GetSize();i++)
	{
		m_cmbBaudrate.AddString(arrBaudRate.GetAt(i));
	}
	
	ASSERT(m_pXmlConfigParse != NULL);

    m_cmbPort.AddString( ALL_PORT );
	
	// Search valible serial ports and open them
    HKEY  hOpenKey;
    const cLen = 255;
    DWORD dwValueLen;
    DWORD dwDataLen;
    _TCHAR szValueName[cLen];
    _TCHAR szData[cLen];
    DWORD dwType;
    DWORD dwRet;    
	
    if((dwRet =RegOpenKeyEx(HKEY_LOCAL_MACHINE, 
		_T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
		NULL,
		KEY_QUERY_VALUE | KEY_READ,
		&hOpenKey)) == ERROR_SUCCESS)
    {
		i = 0;
        while(1)
        {
            dwValueLen = cLen;
            dwDataLen = cLen;
            szValueName[0] = 0;
            szData[0] = 0;
            
            dwRet = ::RegEnumValue(hOpenKey,
                i++,
                szValueName,
                &dwValueLen,
                NULL,
                &dwType,
                (BYTE*)szData,
                &dwDataLen
                );
            
            if(dwRet != ERROR_SUCCESS )
                break;
            
            int port;
            int nRet = _stscanf(szData,_T("COM%d"),&port);
            
            if(nRet == 0)
                continue;
            
            m_cmbPort.AddString( szData );
        }    
        RegCloseKey(hOpenKey);
    }
	
    CString strText;  
    int iSelPort = 0;
    if( m_nComPort != 0 )
    {
        strText.Format(_T("COM%d"),m_nComPort );
        
        iSelPort = m_cmbPort.FindString(0,strText);
        if( iSelPort == CB_ERR)
        {
            // Default is all
            iSelPort = 0;	
        }        
    }
    m_cmbPort.SetCurSel( iSelPort );
	
    strText.Format(_T("%d"),m_nBaudRate);
	
	int iSelBaudRate = m_cmbBaudrate.FindString(0,strText);
	if(iSelBaudRate == CB_ERR)
	{
		// Default is 115200
		iSelBaudRate = 1;	
	}
    m_cmbBaudrate.SetCurSel(iSelBaudRate);

	m_bAllFiles = TRUE;

	if(m_nProductCount>0)
	{
		for(i=0;i<m_nProductCount;i++)
			m_cmbProduct.AddString(m_arrProductName[i]);
	}

	//m_lstProduct
	m_lstProductInfo.SetBkColor(RGB(232, 232, 232));	
	m_lstProductInfo.ModifyStyle(0, LVS_SHOWSELALWAYS);
	
	DWORD dwExStyle = m_lstProductInfo.GetExtendedStyle();
	dwExStyle |= LVS_EX_FULLROWSELECT;
	dwExStyle |= LVS_EX_GRIDLINES;

//#ifdef _SPUPGRADE
	if(m_bCanSel)
	{
		dwExStyle |= LVS_EX_CHECKBOXES;
	}
	else
	{
		GetDlgItem(IDC_CHK_ALL)->ShowWindow(SW_HIDE);
	}
/*#elif defined _DOWNLOAD_FOR_PRODUCTION
	if(m_bCanSel)
	{
		dwExStyle |= LVS_EX_CHECKBOXES;
	}
#else	
	dwExStyle |= LVS_EX_CHECKBOXES;
#endif*/	
	
	m_lstProductInfo.SetExtendedStyle(dwExStyle);

//Load Column
	CString strClmn;
	VERIFY( strClmn.LoadString(IDS_PRODUCT_INFO_COLUMN) );
	
	nLen   = strClmn.GetLength();
	lpBuf  = strClmn.GetBuffer(nLen);
	lpFind = _tcschr(lpBuf, _T(','));
	int     nIndex = 0;
	while(lpFind != NULL)
	{
		*lpFind = _T('\0');
		if(nIndex == 1)
			m_lstProductInfo.InsertColumn(nIndex++,lpBuf,LVCFMT_LEFT,250);
		else
			m_lstProductInfo.InsertColumn(nIndex++,lpBuf,LVCFMT_LEFT,110);
		lpBuf = lpFind + 1;
		lpFind = _tcschr(lpBuf, _T(','));
	}
	m_lstProductInfo.InsertColumn(nIndex, lpBuf, LVCFMT_LEFT, 100 );
	strClmn.ReleaseBuffer();


	if(m_strCurProduct.IsEmpty())
	{
		m_nCurProduct = 0;
		m_strCurProduct = m_arrProductName.GetAt(0);
		
		m_nTmpProduct = m_nCurProduct;
		m_strTempProduct = m_strCurProduct;
	}

    FillList(m_strCurProduct);
	m_lstProductInfo.EnableToolTips();
	
	m_cmbProduct.SetCurSel(m_nCurProduct);
	
#ifdef _SPUPGRADE
	CStatic *pwnd = (CStatic *)GetDlgItem(IDC_STC_SEL_PRD);
	if(pwnd != NULL)
	{
		pwnd->SetWindowText(_T("          Product:"));
	}
	GetDlgItem(IDC_CMB_PRODUCT)->EnableWindow(FALSE);
	
#elif defined _DOWNLOAD_FOR_PRODUCTION	
	CStatic *pwnd = (CStatic *)GetDlgItem(IDC_STC_SEL_PRD);
	if(pwnd != NULL)
	{
		pwnd->SetWindowText(_T("          Product:"));
	}
	GetDlgItem(IDC_CMB_PRODUCT)->EnableWindow(FALSE);
#else
	GetDlgItem(IDC_EDT_PRD_VERSION)->ShowWindow(SW_HIDE);
#endif

	UpdateData(FALSE);

	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CMainPage::LoadSettings(LPCTSTR pFileName)
{
//ini first
	ASSERT(NULL != pFileName);
    if(NULL == pFileName)
    {
        return FALSE;
    }   
    m_strIniFile = pFileName;

	CMainFrame *pMF = (CMainFrame *)AfxGetMainWnd();
	if(pMF!= NULL && pMF->m_bPacketOpen)
	{
		return LoadConfig(pFileName);
	}


    // Get Default Baudrates	
    _TCHAR szBaudSection[MAX_PATH];
    memset(szBaudSection,0,MAX_PATH);
	::GetPrivateProfileString(g_sz_SEC_GUI,g_sz_KEY_BRS,g_sz_BR_DEFAULT,szBaudSection,MAX_PATH,pFileName);

	CString strBaudRate;
	strBaudRate = szBaudSection;
	if(!strBaudRate.IsEmpty())
    {
		m_arrBaudRateConfig.RemoveAll();
		int     nLen   = strBaudRate.GetLength();
		LPTSTR  lpBuf  = strBaudRate.GetBuffer(nLen);
		LPTSTR  lpFind = _tcschr(lpBuf, _T(','));
		while(lpFind != NULL)
		{
			*lpFind = _T('\0');

			m_arrBaudRateConfig.Add(lpBuf);
			lpBuf = lpFind + 1;
			lpFind = _tcschr(lpBuf, _T(','));
		}
		m_arrBaudRateConfig.Add(lpBuf);
		strBaudRate.ReleaseBuffer();
    }

    // Get baudrate
    m_nBaudRate = ::GetPrivateProfileInt(g_sz_SP,g_sz_BR,115200,pFileName);
    m_nComPort = ::GetPrivateProfileInt( g_sz_SP, g_sz_PORT, 0, pFileName );

#ifdef _SPUPGRADE
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 0, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 0, pFileName );
#else
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 1, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 1, pFileName );
#endif
	
#ifdef _DOWNLOAD_FOR_PRODUCTION
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 0, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 0, pFileName );
#endif

	m_wLangNVItemID = (WORD)::GetPrivateProfileInt( g_sz_SEC_NV, g_sz_KEY_LNII, NV_MULTI_LANG_ID, pFileName );

	m_bEnableChipDspMap = ::GetPrivateProfileInt( g_sz_SEC_CHIPDSPMAP, g_sz_KEY_CDME, FALSE, pFileName );

	_TCHAR szSection[MAX_BUF_SIZE]={0}; 
    
    ::GetPrivateProfileString(g_sz_SELECT,g_sz_SELECT_PRODUCT,NULL,szSection,MAX_BUF_SIZE,pFileName);
    m_strCurProduct = szSection;
    
    _TCHAR szKeyValue[ MAX_BUF_SIZE ]={0}; //hongliang.xin 2007-12-11 for ocupying CPU 50%
    GetPrivateProfileSection( m_strCurProduct, szKeyValue, MAX_BUF_SIZE, pFileName );
    
	m_arrAllFileName.RemoveAll();
	CStringArray arrKeyData;    
	UINT nFileCount = (UINT)EnumKeys(szKeyValue,&arrKeyData);
	UINT i=0;
	m_aFileCheckState.RemoveAll();
	CString strCheckFile;
	CString strCheck;
	int nCheck;
	int nFind = -1;
	CString strFDL2;
	for(i=0;i<nFileCount;i++)
	{
		strCheckFile = arrKeyData[i*2+1];
		strCheckFile.TrimLeft();
		if(strCheckFile.IsEmpty())
		{
			m_aFileCheckState.Add(0);
		}
		else
		{
			nFind = strCheckFile.Find(_T('@'));
			if(nFind == -1 || nFind > 1)
			{
				m_aFileCheckState.Add(1);
			}
			else
			{
				strCheck = strCheckFile.Left(nFind);
				nCheck = _ttoi(strCheck);
				if(nCheck != 0)
					nCheck = 1;
				m_aFileCheckState.Add(nCheck);
				strCheckFile = strCheckFile.Right(strCheckFile.GetLength()-nFind-1);
			}
		}
        TRACE(_T("%d\n"),m_aFileCheckState.GetAt(i));
		m_arrAllFileName.Add(strCheckFile);
		if( m_aFileCheckState.GetAt(i)==1 )
		{
			m_arrFileName.Add(strCheckFile);
		}
		else
		{
			m_arrFileName.Add(FILE_OMIT);
		}

		if(arrKeyData[i*2].CompareNoCase(_T("FDL2")) == 0)
		{
			strFDL2 = strCheckFile;
		}
		
	}    
 
	
	BOOL bFDL = FALSE;
	if(m_arrFileName.GetSize()>0 )
	{
		if(!m_arrFileName.GetAt(0).IsEmpty() && m_arrAllFileName.GetAt(0).Compare(FILE_OMIT) != 0)
			bFDL = TRUE;
	}
	if(!m_strCurProduct.IsEmpty() && bFDL  )
		m_bInit = TRUE;

	CString strXMLConfig = GetXmlFile(pFileName);

    if(!LoadAllProduct(strXMLConfig))
		return FALSE;

	if(m_pCurProductInfo != NULL)
	{
		if(m_pCurProductInfo->dwOmaDMFlag != 0)
		{
			m_bOmaDM = m_bTmpOmaDM = GetFdl2Flag(strFDL2,FDL2F_OMADM);
			m_bPreload = m_bTmpPreload = GetFdl2Flag(strFDL2,FDL2F_PRELOAD);
			m_bKernelImg2 = m_bTmpKernelImg2 = GetFdl2Flag(strFDL2,FDL2F_KERNELIMG2);
			m_bRomDisk = m_bTmpRomDisk = GetFdl2Flag(strFDL2,FDL2F_ROMDISK);
		}
	}

	InitCaliPage(m_pCurProductInfo);
	InitMultiLangPage();
	
    return TRUE;
}

BOOL CMainPage::SaveSettings(LPCTSTR pFileName)
{
	ASSERT(NULL != pFileName);
    if(NULL == pFileName)
    {
        return FALSE;
    }
    // Save baudrate 
    CString strTemp;
    strTemp.Format( _T("%d"), m_nComPort );
    ::WritePrivateProfileString( g_sz_SP,g_sz_PORT,strTemp,pFileName);
    strTemp.Format(_T("%d"),m_nBaudRate);
    ::WritePrivateProfileString( g_sz_SP,g_sz_BR,strTemp,pFileName);
    
	// save selected product
	::WritePrivateProfileString(g_sz_SELECT,g_sz_SELECT_PRODUCT,m_strCurProduct,pFileName);

	CMainFrame * pMF = (CMainFrame *)AfxGetMainWnd();
	BOOL bPacketMode = FALSE;
    if(pMF != NULL)
	{
		if(pMF->m_bPacketOpen)
		{
			bPacketMode= TRUE;
		}
	}

	strTemp.Format( _T("%d"), bPacketMode );
	::WritePrivateProfileString(g_sz_SEC_GUI,_T("PacketMode"),strTemp,pFileName);

    // Save download files' names
	// Save omitted file also 	
	// first delete old files 
	::WritePrivateProfileString( g_sz_SEC_DF,NULL,NULL,pFileName);
	CString strFilePath;
	CString strFileID;
	int nItem = m_lstProductInfo.GetItemCount();
	CString strCheckFile;
	for(int i = 0; i<nItem && !m_strCurProduct.IsEmpty(); i++)
	{
		strFileID = m_pTmpProductInfo->pFileInfoArr[i].szID;
		strFilePath = m_lstProductInfo.GetItemText(i,1);
		strCheckFile.Format(_T("%d@%s"),m_lstProductInfo.GetCheck(i),strFilePath);
		WritePrivateProfileString( m_strCurProduct, strFileID,strCheckFile, pFileName );

	}

    return TRUE;
}

void CMainPage::OnOK() 
{
	// TODO: Add your specialized code here and/or call the base class
    
    CString strText;
	
    m_cmbPort.GetWindowText( strText );
    if( _tcscmp( strText, ALL_PORT ) == 0 )
    {
        m_nComPort = 0;
    }
    else
    {
        _stscanf( strText, _T("COM%d"), &m_nComPort );
    }
    
    m_cmbBaudrate.GetWindowText(strText);
    m_nBaudRate = _ttoi(strText);

	m_arrFileName.RemoveAll();
	m_arrAllFileName.RemoveAll();
    int nCount = m_lstProductInfo.GetItemCount();
	m_aFileCheckState.RemoveAll();
	for(int i=0;i<nCount;i++)
	{
		m_arrAllFileName.Add(m_lstProductInfo.GetItemText(i,1));		
		m_aFileCheckState.Add(m_lstProductInfo.GetCheck(i));

		if(m_lstProductInfo.GetCheck(i))
		{
			m_arrFileName.Add(m_lstProductInfo.GetItemText(i,1));
		}
		else
		{
			m_arrFileName.Add(FILE_OMIT);
 		}		
	}
	
	m_cmbProduct.GetWindowText(m_strCurProduct);
	m_nCurProduct = m_cmbProduct.GetCurSel();

    if(m_nCurProduct != -1)
		m_pCurProductInfo = m_vctProductInfo[m_nCurProduct];
	
	BOOL bCheck = FALSE;
	if(m_arrFileName.GetSize()>0 )
	{
		if(!m_arrFileName.GetAt(0).IsEmpty() && m_lstProductInfo.GetCheck(i))
			bCheck = TRUE;
	}
	if(!m_strCurProduct.IsEmpty() && bCheck  )
		m_bInit = TRUE;
	

	m_bOmaDM = m_bTmpOmaDM;
	m_bPreload = m_bTmpPreload;
	m_bKernelImg2 = m_bTmpKernelImg2;
	m_bRomDisk = m_bTmpRomDisk;

	CMainFrame * pMF = (CMainFrame *)AfxGetMainWnd();

	if(m_strCurProduct.Find(_T("PAC_")) != 0)
	{
		CString strTmp;
		strTmp.Format(_T("%s"),m_strCurProduct);
		if(pMF != NULL)
		{
			pMF->SetPrdVersion(strTmp);
			pMF->m_bPacketOpen = FALSE;
		}
	}
	
	//保存设置
	if(!m_strIniFile.IsEmpty())
	{
		DWORD dwAttr = GetFileAttributes(m_strIniFile);
		if(-1 != dwAttr)
		{
			dwAttr &= ~FILE_ATTRIBUTE_READONLY;
			::SetFileAttributes(m_strIniFile,dwAttr);
		}
		SaveSettings(m_strIniFile);
	}
    
	TRACE(_T("Current Product name: %s\n"),m_pCurProductInfo->szProductName);


	
	CPropertyPage::OnOK();
}

BOOL CMainPage::OnKillActive() 
{
	// TODO: Add your specialized code here and/or call the base class
	this->SetFocus();
	if( !g_bInitSheet)
	{
		CString strErr;
		if(!m_lstProductInfo.GetCheck(0))
		{
			AfxMessageBox(IDS_ERR_FDL_NOT_CHECKED);
			m_lstProductInfo.SetCheck(0);
			return FALSE;
		}
		int nCount = m_lstProductInfo.GetItemCount();
		for(int i = 0;i<nCount;i++)
		{
			if(m_lstProductInfo.GetCheck(i) && LOWORD(m_lstProductInfo.GetItemData(i))!=0)
			{
				if(m_lstProductInfo.GetItemText(i,1).IsEmpty())
				{
					AfxMessageBox(IDS_ERR_FILE_EMPTY);
					return FALSE;
				}
			}
		}

		CSettingsSheet* pParentWnd = NULL;
		pParentWnd = (CSettingsSheet*)GetParent();
		CString strCurProduct;
		m_cmbProduct.GetWindowText(strCurProduct);
		int nSel = m_cmbProduct.GetCurSel();

		PPRODUCT_INFO_T pProdInfo = m_vctProductInfo[nSel];

		if(m_pCaliPage->m_strTempCurProduct.IsEmpty() || 
			m_pCaliPage->m_strTempCurProduct.CompareNoCase(strCurProduct)!=0 )
		{

			pParentWnd->m_pageCalibration.m_lstBackup.AddNvBackupItemInfo(pProdInfo->paNvBackupItem,
											pProdInfo->dwNvBackupItemCount);
			pParentWnd->m_pageCalibration.m_strTempCurProduct = strCurProduct;

		}
		
		InitMultiLangPage(TRUE);
	}
	
	return CPropertyPage::OnKillActive();
}

void CMainPage::OnSelchangeCmbProduct() 
{
	// TODO: Add your control notification handler code here
    CString strProduct;
	m_cmbProduct.GetWindowText(strProduct);
//	m_nCurProduct = m_cmbProduct.GetCurSel();
	GetDlgItem(IDC_CHK_ALL)->EnableWindow(TRUE);
	m_bAllFiles = TRUE;
	FillList(strProduct);

	UpdateData(FALSE);
}

BOOL CMainPage::OnSetActive() 
{
	// TODO: Add your specialized code here and/or call the base class
	
	return CPropertyPage::OnSetActive();
}


BOOL CMainPage::FillList(LPCTSTR lpcstrProduct)
{
	ASSERT(m_pXmlConfigParse != NULL);
	if(lpcstrProduct==NULL)
		return TRUE;

	int nProduct = GetProductIndex(lpcstrProduct);
	if(nProduct == -1)
		return FALSE;

	m_nTmpProduct = nProduct;

	m_strTempProduct = lpcstrProduct;
	
	PPRODUCT_INFO_T pProdInfo = m_vctProductInfo[nProduct];
	m_pTmpProductInfo = pProdInfo;

	DWORD dwCount=pProdInfo->dwFileCount;
    PFILE_INFO_T pFileInfo = pProdInfo->pFileInfoArr;


	CString strComment = pProdInfo->szComment;
	m_stcProdComment.SetText(strComment);

#ifdef _SPUPGRADE
	CString strVer = m_strPrdVersion;
	strVer.MakeUpper();
	m_edtPrdVersion.SetWindowText(strVer);
#endif
#ifdef _DOWNLOAD_FOR_PRODUCTION
	CString strVer = m_strPrdVersion;
	strVer.MakeUpper();
	m_edtPrdVersion.SetWindowText(strVer);
#endif
	
	m_lstProductInfo.DeleteAllItems();

	UINT i=0;
	UINT j=0;
	CString str;
	for(i=0;i<dwCount;i++)
	{
		m_bListInsertItemComlpete = FALSE;
		m_lstProductInfo.InsertItem(i,pFileInfo[i].szIDAlias);
		m_bListInsertItemComlpete = TRUE;

        UINT nBlock = pFileInfo[i].dwBlockCount;
//		ASSERT(nBlock<=2);
//      支持两个
		if(nBlock > 5)
			nBlock = 5;

		for(j=0;j<nBlock;j++)
		{
			str.Format(_T("0x%X"),pFileInfo[i].arrBlock[j].dwBase);
			m_lstProductInfo.SetItemText(i,2+j*2,str);
#ifdef _SPUPGRADE
			if(j==0 && pFileInfo[i].dwFlag != 0)
			{
				str.Format(_T("0x%X"),m_aFileSize[i]);
			}
			else
			{
				str.Format(_T("0x%X"),pFileInfo[i].arrBlock[j].dwSize);
			}
#elif defined _DOWNLOAD_FOR_PRODUCTION
			if(j==0 && pFileInfo[i].dwFlag != 0)
			{
				str.Format(_T("0x%X"),m_aFileSize[i]);
			}
			else
			{
				str.Format(_T("0x%X"),pFileInfo[i].arrBlock[j].dwSize);
			}
#else
			str.Format(_T("0x%X"),pFileInfo[i].arrBlock[j].dwSize);
#endif
			if(str.CompareNoCase(_T("0x0"))==0)
			{
				str = _T("");
			}
			m_lstProductInfo.SetItemText(i,3+j*2,str);
		}
		m_lstProductInfo.SetItemText(i,12,pFileInfo[i].szType);
		DWORD dwItemData = pFileInfo[i].dwFlag;
		if(	pFileInfo[i].dwCheckFlag == 2 )
		{
			dwItemData = DI_SET_OMIT(dwItemData);
		}
		m_lstProductInfo.SetItemData(i,dwItemData);
		m_lstProductInfo.SetCheck(i);
		
	}

	CString strFDL2Path;
	strFDL2Path.Empty();

	if(lpcstrProduct!=NULL && m_strCurProduct.CompareNoCase(lpcstrProduct)==0 && (UINT)m_arrAllFileName.GetSize() == dwCount)
	{
		for(i=0;i<dwCount;i++)
		{
			m_lstProductInfo.SetItemText(i,1,m_arrAllFileName.GetAt(i));


			//if(m_arrFileName.GetAt(i).CompareNoCase(FILE_OMIT)!=0)
			if(m_aFileCheckState.GetAt(i) == 1)
			{
				//m_lstProductInfo.SetItemText(i,1,m_arrFileName.GetAt(i));
				m_lstProductInfo.SetCheck(i);
			}
			else
			{
				if(pFileInfo[i].dwCheckFlag == 1)
				{
					m_lstProductInfo.SetCheck(i);
					continue;
				}
				m_lstProductInfo.SetCheck(i,FALSE);
				m_bAllFiles = FALSE;				
			}	

			if(m_pTmpProductInfo->dwOmaDMFlag != 0)
			{
				//CString strFileID = m_lstProductInfo.GetItemText(i,0);
				CString strFileID = pFileInfo[i].szID;
				if(strFileID.CompareNoCase(_T("FDL2")) == 0)
				{
					strFDL2Path = m_arrAllFileName.GetAt(i);
					m_bTmpOmaDM = GetFdl2Flag(strFDL2Path,FDL2F_OMADM);
					m_bTmpPreload = GetFdl2Flag(strFDL2Path,FDL2F_PRELOAD);
					m_bTmpKernelImg2 = GetFdl2Flag(strFDL2Path,FDL2F_KERNELIMG2);
					m_bTmpRomDisk = GetFdl2Flag(strFDL2Path,FDL2F_ROMDISK);
				}
				else if(strFileID.CompareNoCase(g_szUA) == 0 || strFileID.CompareNoCase(g_szEDU) == 0)
				{
					DWORD dwData = m_lstProductInfo.GetItemData(i);
					if(!m_bTmpOmaDM)
					{
						dwData = DI_SET_GRAY(dwData);
					}
					else
					{
						dwData = DI_UNSET_GRAY(dwData);
					}

					m_lstProductInfo.SetItemData(i,dwData);
					GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
				}
				else if(strFileID.CompareNoCase(g_szPreload) == 0)
				{
					DWORD dwData = m_lstProductInfo.GetItemData(i);
					if(!m_bTmpPreload)
					{				
						dwData = DI_SET_GRAY(dwData);
					}
					else
					{
						dwData = DI_UNSET_GRAY(dwData);
					}

					m_lstProductInfo.SetItemData(i,dwData);
					GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2&& m_bTmpRomDisk);
				}
				else if(strFileID.CompareNoCase(g_szKernelImg2) == 0)
				{
					DWORD dwData = m_lstProductInfo.GetItemData(i);
					if(!m_bTmpKernelImg2)
					{				
						dwData = DI_SET_GRAY(dwData);
					}
					else
					{
						dwData = DI_UNSET_GRAY(dwData);
					}

					m_lstProductInfo.SetItemData(i,dwData);
					GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2&& m_bTmpRomDisk);
				}
				else if(strFileID.CompareNoCase(g_szRomDisk) == 0)
				{
					DWORD dwData = m_lstProductInfo.GetItemData(i);
					if(!m_bTmpRomDisk)
					{				
						dwData = DI_SET_GRAY(dwData);
					}
					else
					{
						dwData = DI_UNSET_GRAY(dwData);
					}

					m_lstProductInfo.SetItemData(i,dwData);
					GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2&& m_bTmpRomDisk);
				}
			}
		}
	}
	return TRUE;
}

LPCTSTR CMainPage::GetXmlFile(LPCTSTR pFileName)
{
	static _TCHAR szXmlFile[MAX_PATH] = {0};
	_tcscpy(szXmlFile,pFileName);
	_TCHAR * p = _tcsrchr(szXmlFile,_T('\\'));
	if(p == NULL)
	{
		return NULL;
	}
	*p=0;
	_tcscat(szXmlFile,_T("\\BMAConfig.xml"));
	return szXmlFile;
}

BOOL CMainPage::LoadAllProduct(LPCTSTR lpszXMLConfig)
{
	if(lpszXMLConfig == NULL)
		return FALSE;

   	if(m_pXmlConfigParse == NULL)
	{
		if(!CreateXmlConfigParse(&m_pXmlConfigParse))
		{
			return FALSE;
		}
	}
	
	CString strXmlFile = lpszXMLConfig;
    if(strXmlFile.IsEmpty())
		return FALSE;
	if(!m_pXmlConfigParse->Init(strXmlFile))
		return FALSE;

	CString strSpecConfig = _T("");

	CMainFrame *pMF = (CMainFrame *)AfxGetMainWnd();
	if(pMF != NULL)
	{
		strSpecConfig = pMF->GetSpecConfigFile();
	}

	if(!m_pXmlConfigParse->Init(strXmlFile))
 			return FALSE;

    if(!strSpecConfig.IsEmpty())
	{
		if(!m_pXmlConfigParse->Init(strSpecConfig,1)) // for special configure
			return FALSE;
	}

	m_arrProductName.RemoveAll();
	m_nProductCount = m_pXmlConfigParse->GetProductCount();

	if(m_nProductCount == 0)
		return FALSE;

	DWORD dwSize = 2000;
	DWORD dwRealSize = 0;
	_TCHAR *psz = new _TCHAR[dwSize];
	memset(psz,0,sizeof(_TCHAR)*dwSize);
	m_pXmlConfigParse->GetProductNameList(psz,dwSize,dwRealSize);
    _TCHAR *pNext = NULL;
	_TCHAR *pCur = psz;
	for(int j = 0;j<m_nProductCount;j++)
	{
		_TCHAR sz[200] = {0};
		pNext = _tcschr(pCur,_T(';'));
		memcpy(sz,pCur,(pNext-pCur)*sizeof(_TCHAR));
		pCur = pNext+1;
		m_arrProductName.Add(sz);
	}
	delete []psz;


	ClearProdInfoVector();
	m_mapPrdCfg.RemoveAll();
	
	PPRODUCT_INFO_T pProdInfo = NULL;
	PPRODUCT_INFO_T pTmpProdInfo = NULL;
	FILE_INFO_ARR arrFileInfo;
	BOOL bMach = FALSE;
	UINT i=0;
	for(i=0; i<(UINT)m_nProductCount; i++)
	{		
		pTmpProdInfo = NULL;
		pTmpProdInfo = m_pXmlConfigParse->GetProdInfo(m_arrProductName[i]);
		_ASSERTE(pTmpProdInfo != NULL);

		pProdInfo = new PRODUCT_INFO_T;

		DeepCopyProductInfo(pProdInfo,pTmpProdInfo);


		m_vctProductInfo.push_back(pProdInfo);
		CString strCfgFile = m_pXmlConfigParse->GetConfigFile(m_arrProductName[i]);
		m_mapPrdCfg.SetAt(m_arrProductName[i],strCfgFile);
		if(m_arrProductName[i].CompareNoCase(m_strCurProduct) == 0)
		{
			m_nCurProduct = i;
			m_pCurProductInfo = pProdInfo;
			bMach = TRUE;

			m_nTmpProduct = m_nCurProduct;
			m_pTmpProductInfo = m_pCurProductInfo;
			m_strTempProduct = m_strCurProduct;	
		}
		
	}

	if(!bMach)
	{
		m_nCurProduct = 0;
		m_pCurProductInfo = m_vctProductInfo[0];
		m_strCurProduct = m_arrProductName[0];
		m_arrFileName.RemoveAll();
		m_arrAllFileName.RemoveAll();
        m_bInit = FALSE;

		m_nTmpProduct = m_nCurProduct;
		m_pTmpProductInfo = m_pCurProductInfo;
		m_strTempProduct = m_strCurProduct;
		
	}

	return TRUE;
}


int CMainPage::GetProductIndex(LPCTSTR lpcstrProuct)
{
	int nCount = m_arrProductName.GetSize();
	int i=0;
	for(i=0;i<nCount;i++)
	{
		if(m_arrProductName.GetAt(i).Compare(lpcstrProuct) == 0)
		     break;
	}
	if(i>=nCount)
		return -1;
	else
		return i;
}

void CMainPage::OnChkAll() 
{
	// TODO: Add your control notification handler code here
	UpdateData();

	int nProduct = GetProductIndex(m_strTempProduct);
	PPRODUCT_INFO_T pProdInfo = m_vctProductInfo[nProduct];
    PFILE_INFO_T pFileInfo = pProdInfo->pFileInfoArr;

	int nCount = m_lstProductInfo.GetItemCount();
	CString strID;
	for(int i =0; i<nCount; i++)
	{
		strID = m_pTmpProductInfo->pFileInfoArr[i].szID;
		
		if(pFileInfo[i].dwCheckFlag != 1) // maybe 0, 2
		{
#ifdef _SPUPGRADE	
			if(strID.CompareNoCase(_T("FLASH"))== 0)
			{
				continue;
			}
#endif
			m_lstProductInfo.SetCheck(i,m_bAllFiles);
		}

	}
}

void CMainPage::OnDblclkLstProductInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
//#ifdef _SPUPGRADE
	if(!m_bCanEdit)
	{
		*pResult = 0;
		return;
	}
//#endif
	
	LPNMITEMACTIVATE pnia = (LPNMITEMACTIVATE)pNMHDR;

	CEdtBtnCtrl *pCtrl = NULL;
	int nItem = pnia->iItem;
	int nSubItem = pnia->iSubItem;
	if(nItem == -1 || nSubItem != 1)
		return;
	if(LOWORD(m_lstProductInfo.GetItemData(nItem)) == 0)
		return;
	
	pCtrl = new CEdtBtnCtrl();

	if(NULL != pCtrl)
	{
		pCtrl->m_nItem = nItem;
		pCtrl->m_nSubItem = nSubItem;
		pCtrl->m_strText = m_lstProductInfo.GetItemText(nItem,nSubItem);
		if(!pCtrl->Create(IDD_EDT_BTN_DLG,FromHandle(m_lstProductInfo.m_hWnd)))
		{
			AfxMessageBox(_T("Error to create EdtBtnCtrl"));
			return;
		}
	}
	else
	{
		return;
	}

	CRect rect;
	m_lstProductInfo.GetSubItemRect(nItem,nSubItem,LVIR_BOUNDS,rect);
	CRect rtList;
	m_lstProductInfo.GetClientRect(&rtList);
	if(rect.right>rtList.right)
		rect.right = rtList.right;
	if(rect.left < rtList.left)
		rect.left = rtList.left;
	if(rect.bottom>rtList.bottom)
		rect.bottom = rtList.bottom;
	if(rect.top < rtList.top)
		rect.top = rtList.top;
	
	pCtrl->SetWindowPos(&wndTop,rect.left,rect.top-1,rect.right-rect.left,rect.bottom-rect.top,NULL);
	
    pCtrl->ShowWindow(SW_SHOW);
	
	*pResult = 0;

}

void CMainPage::OnEndlabeleditLstProductInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_lstProductInfo.SetItemText(pDispInfo->item.iItem,pDispInfo->item.iSubItem,pDispInfo->item.pszText);
	if(m_pTmpProductInfo->dwOmaDMFlag != 0)
	{
		//CString fileID = m_lstProductInfo.GetItemText(pDispInfo->item.iItem,0);
		CString fileID = m_pTmpProductInfo->pFileInfoArr[pDispInfo->item.iItem].szID;
		if(fileID.CompareNoCase(_T("FDL2"))== 0)
		{
			m_bTmpOmaDM= GetFdl2Flag(pDispInfo->item.pszText,FDL2F_OMADM);
			m_bTmpPreload= GetFdl2Flag(pDispInfo->item.pszText,FDL2F_PRELOAD);
			m_bTmpKernelImg2 = GetFdl2Flag(pDispInfo->item.pszText,FDL2F_KERNELIMG2);
			m_bTmpRomDisk = GetFdl2Flag(pDispInfo->item.pszText,FDL2F_ROMDISK);
	
// 			if(!m_bTmpOmaDM)
			{
				for(int i= 0; i< m_lstProductInfo.GetItemCount();i++)
				{
					//fileID =  m_lstProductInfo.GetItemText(i,0);
					fileID =  m_pTmpProductInfo->pFileInfoArr[i].szID;
					if(fileID.CompareNoCase(g_szUA)==0 || fileID.CompareNoCase(g_szEDU)==0 )
					{
						m_lstProductInfo.SetCheck(i,m_bTmpOmaDM);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpOmaDM)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}

						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}					
					else if(fileID.CompareNoCase(g_szPreload)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpPreload);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpPreload)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}

						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
					else if(fileID.CompareNoCase(g_szKernelImg2)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpKernelImg2);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpKernelImg2)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}

						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
					else if(fileID.CompareNoCase(g_szRomDisk)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpRomDisk);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpRomDisk)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}

						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
				}
			}
		
		}
	}


	*pResult = 0;
}


void CMainPage::OnItemchangedLstProductInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	if(pNMListView->iItem < 0 || pNMListView->iSubItem != 0 )
		return;
	// TODO: Add your control notification handler code here
	if(pNMListView->uNewState == 0x00001000 ) // uncheck
	{
		m_bAllFiles = FALSE;
	}
	else if(pNMListView->uNewState == 0x00002000) // check
	{
		int nItem = m_lstProductInfo.GetItemCount();
		int i = 0;
		for(i = 0; i< nItem; i++)
		{
			if(!m_lstProductInfo.GetCheck(i))
				break;
		}
		if(i>= nItem)
			m_bAllFiles = TRUE;
	}

	int nProduct = GetProductIndex(m_strTempProduct);
	PPRODUCT_INFO_T pProdInfo = m_vctProductInfo[nProduct];
    PFILE_INFO_T pFileInfo = pProdInfo->pFileInfoArr;

    CString strFileID;
	strFileID = pFileInfo[pNMListView->iItem].szID;
	CString strText = m_lstProductInfo.GetItemText(pNMListView->iItem,0);

	if(m_bCanSel)
	{
#ifdef _SPUPGRADE
		if(strFileID.CompareNoCase(_T("FLASH"))== 0 && pNMListView->uNewState == 0x00001000 && m_bListInsertItemComlpete)
		{
			AfxMessageBox(_T("Must select flash!!!"));
			m_lstProductInfo.SetCheck(pNMListView->iItem);
		}
#endif
		if(pFileInfo[pNMListView->iItem].dwCheckFlag == 1 && pNMListView->uNewState == 0x00001000 && m_bListInsertItemComlpete)
		{
			CString strWarning;
			strWarning.Format(_T("Must select %s!!!"),strText);
			AfxMessageBox(strWarning);
			m_lstProductInfo.SetCheck(pNMListView->iItem);
		}

		if((strFileID.CompareNoCase(g_szUA)== 0 || strFileID.CompareNoCase(g_szEDU)== 0 )&&
			pNMListView->uNewState == 0x00002000 && m_bListInsertItemComlpete && !m_bTmpOmaDM)
		{
			m_lstProductInfo.SetCheck(pNMListView->iItem,FALSE);
		}
		else if(strFileID.CompareNoCase(g_szPreload)== 0 && pNMListView->uNewState == 0x00002000 
			&& m_bListInsertItemComlpete && !m_bTmpPreload)
		{	
			m_lstProductInfo.SetCheck(pNMListView->iItem,FALSE);
		}
		else if(strFileID.CompareNoCase(g_szKernelImg2)== 0 && pNMListView->uNewState == 0x00002000 
			&& m_bListInsertItemComlpete && !m_bTmpKernelImg2)
		{	
			m_lstProductInfo.SetCheck(pNMListView->iItem,FALSE);
		}
		else if(strFileID.CompareNoCase(g_szRomDisk)== 0 && pNMListView->uNewState == 0x00002000 
			&& m_bListInsertItemComlpete && !m_bTmpRomDisk)
		{	
			m_lstProductInfo.SetCheck(pNMListView->iItem,FALSE);
		}

	}

	
    UpdateData(FALSE);
	*pResult = 0;
}

void CMainPage::InitCaliPage(PPRODUCT_INFO_T pCurProduct)
{
    ASSERT(m_pCaliPage != NULL);
	ASSERT(pCurProduct != NULL);

    m_pCaliPage->m_strCurProduct = m_strCurProduct;
	m_pCaliPage->m_strTempCurProduct = m_strCurProduct;
	
//	m_pCaliPage->m_lstBackup.DeleteAll();
	m_pCaliPage->m_lstBackup.InitNvBackupInfo(pCurProduct->paNvBackupItem,pCurProduct->dwNvBackupItemCount);
}

void CMainPage::InitNandPage()
{
	m_pNandPage->m_nFlashType = m_bph.dwNandPageType;
	m_pNandPage->m_nRepartitionFlag = m_bph.dwNandStrategy;
}

void CMainPage::InitMultiLangPage(BOOL bUpdateWnd)
{
	CUIntArray agLangFlag;
	int nNVItem = GetFileInfo(_T("NV"),NULL,bUpdateWnd);
	CString strNVFile;
	BOOL bNVCheck = TRUE;
	FILETIME ft;
	memset(&ft,0,sizeof(FILETIME));

	if(bUpdateWnd)
	{
		if(nNVItem != -1 && nNVItem < m_lstProductInfo.GetItemCount())
		{
			strNVFile = m_lstProductInfo.GetItemText(nNVItem,1);
			bNVCheck = m_lstProductInfo.GetCheck(nNVItem);
		}
		else
		{
			bNVCheck = FALSE;
			strNVFile.Empty();
		}
	}
	else
	{
		if(nNVItem != -1 && nNVItem < m_arrFileName.GetSize())
		{
			strNVFile = m_arrFileName.GetAt(nNVItem);
			if(strNVFile.CompareNoCase(FILE_OMIT) == 0)
			{
				bNVCheck = FALSE;
				strNVFile.Empty();
			}
		}
		else
		{
			bNVCheck = FALSE;
			strNVFile.Empty();
		}
	}
	if(nNVItem != -1 && !strNVFile.IsEmpty() && bNVCheck
	   && FindLangNVItem(strNVFile,agLangFlag,&ft) )
	{
		m_pMultiLangPage->SetLangFlag(TRUE,agLangFlag,&ft,bUpdateWnd);	
	}
	else
	{	
		m_pMultiLangPage->SetLangFlag(FALSE,agLangFlag,&ft,bUpdateWnd);
	}
}

BOOL CMainPage::LoadPacket(LPCTSTR lpszPacketName)
{
	_ASSERTE(lpszPacketName != NULL);
	
    CMainFrame * pMF= (CMainFrame *)AfxGetMainWnd();
	pMF->SetPrdVersion(_T(""));

	CBinPack bp;
	if(!bp.Open(lpszPacketName,TRUE))
	{
		return FALSE;
	}

	BIN_PACKET_HEADER_T bph;

	FILE_T *paFile = NULL;
	
	BOOL bOK = bp.Unpacket(NULL,bph,&paFile);
	((CMainFrame *)AfxGetMainWnd())->m_aPacReleaseDir.Add(bp.GetReleaseDir());
    ((CMainFrame *)AfxGetMainWnd())->m_strSpecConfig = bp.GetConfigFilePath();
	bp.Close();
	if(!bOK)
	{
		return FALSE;
	}
	
	m_aFileID.RemoveAll();
	m_arrAllFileName.RemoveAll();
	m_arrFileName.RemoveAll();
	m_arrProductName.RemoveAll();
	m_aFileSize.RemoveAll();
	m_aFileCheckState.RemoveAll();
	
	
	m_strCurProduct = bph.szPrdName;
	m_arrProductName.Add(m_strCurProduct);
	m_nProductCount = 1;

    m_strPrdVersion = bph.szPrdVersion;
// 	m_bOmaDM = bph.dwIsOmaDM;
// 	m_bPreload = bph.dwIsPreload;

	CString strAlias= bph.szPrdAlias;

	FILE_T * pFT = NULL;

	

	BOOL bNvFileSelected = FALSE;
	BOOL bFlashSelected = FALSE;
	BOOL bPhaseCheck = FALSE;

	int nAllowOmit = 0;
	int nRealFileCount = 0;

	for(int i = 0; i< bph.nFileCount; i++)
	{
		pFT = paFile + i;
		m_aFileCheckState.Add(pFT->nCheckFlag);
		m_arrAllFileName.Add(pFT->szFileName);
		m_aFileID.Add(pFT->szFileID);
		m_aFileSize.Add(pFT->nFileSize);
		CString strID = pFT->szFileID;

		if(pFT->dwCanOmitFlag == 1)
		{
			nAllowOmit++;
		}

		if(pFT->nCheckFlag && (_tcslen(pFT->szFileName) != 0 || pFT->nFileFlag == 0 ))
		{
			m_arrFileName.Add(pFT->szFileName);

			nRealFileCount++;

			if(strID.CompareNoCase(_T("NV")) == 0)
			{
				bNvFileSelected = TRUE;
			}
			else if(strID.CompareNoCase(_T("FLASH")) == 0)
			{
				bFlashSelected = TRUE;
			}
			else if(strID.CompareNoCase(_T("PhaseCheck")) == 0)
			{
				bPhaseCheck = TRUE;
			}
			else if(strID.CompareNoCase(_T("FDL2")) == 0)
			{		
				m_bOmaDM = GetFdl2Flag(pFT->szFileName,FDL2F_OMADM);
				m_bPreload = GetFdl2Flag(pFT->szFileName,FDL2F_PRELOAD);
				m_bKernelImg2 = GetFdl2Flag(pFT->szFileName,FDL2F_KERNELIMG2);
				m_bRomDisk = GetFdl2Flag(pFT->szFileName,FDL2F_ROMDISK);
			}

			if(pFT->dwCanOmitFlag == 1)
			{
				nAllowOmit--;
			}

		}
		else
		{
			m_arrFileName.Add(FILE_OMIT);	
		}
	}

    bp.ReleaseMem(paFile);

	BOOL bAllFileDown = FALSE;

	if( (bph.nFileCount - nRealFileCount) == nAllowOmit )
	{
		bAllFileDown = TRUE;
	}


	BOOL bRepartition = FALSE;
	if (bph.dwNandStrategy == REPAR_STRATEGY_ALWAYS || bph.dwNandStrategy ==REPAR_STRATEGY_DO)
		bRepartition = TRUE;

#if defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION) 
	BOOL bNand = (BOOL)(bph.dwFlashType);
#endif

	if(!bFlashSelected)
	{
		AfxMessageBox(_T("Configure dangerouse: have not selected to earase flash.\nPlease select right packet!"));
		return FALSE;
	}

#if 0//defined(_SPUPGRADE)
	BOOL bBackupNV = (BOOL)(bph.dwIsNvBackup);

	if(!bNvFileSelected)
	{
		AfxMessageBox(_T("Configure dangerouse: have not selected NV file to dwonload.\nPlease select right packet!"));
		return FALSE;
	}

	/* bNvFileSelected = TRUE */
	if( !bBackupNV )
	{
		AfxMessageBox(_T("Configure dangerouse: have not selected any NV item to backup.\nPlease select right packet!"));
		return FALSE;
	}

	
	if(!bAllFileDown)
	{
		if(bNand && bRepartition)
		{
			AfxMessageBox(_T("Configure dangerouse: have selected repartition,\nbut not selected all files to download.\nPlease select right packet!"));
			return FALSE;
		}
		else
		{
			// allow to download part files. but prompt the warning.
			AfxMessageBox(_T("Configure dangerouse: have not selected all files to dwonload."));
		}
	}
	else
	{
		if(bNand && bRepartition && !bBackupNV)
		{
			AfxMessageBox(_T("Configure dangerouse: have selected repartition,\nbut not selected all files to download.\nPlease select right packet!"));
			return FALSE;
		}
	}

#endif	

#if 0//defined(_DOWNLOAD_FOR_PRODUCTION)
     /* bph.dwIsNvBackup must be false(0) */
	_ASSERTE(bph.dwIsNvBackup == 0 );
    if (bp.IsExistEmptyFile() && !bAllFileDown)
    {
		AfxMessageBox(_T("Configure dangerouse: exist empty file in package which should not occur in production download.\nPlease select right packet!"));
		return FALSE;
    }
	if (!bPhaseCheck)
	{
		AfxMessageBox(_T("Configure dangerouse: no PhaseCheck information in package which should not occur in production download.\nPlease select right packet!"));
		return FALSE;
	}
	if(!bAllFileDown)
	{
		if(bNand && bRepartition)
		{
			AfxMessageBox(_T("Configure dangerouse: have selected repartition,\nbut not selected all files to download.\nPlease select right packet!"));
			return FALSE;
		}
		else
		{
			// allow to download part files. but prompt the warning.
			AfxMessageBox(_T("Configure dangerouse: have not selected all files to dwonload."));
		}
	}

#endif

	memcpy(&m_bph,&bph,sizeof(bph));

	CString strTmp;
	if(strAlias.IsEmpty())
		strTmp.Format(_T("%s : %s"),m_strCurProduct,m_strPrdVersion);	
	else
		strTmp.Format(_T("%s : %s"),strAlias,m_strPrdVersion);	

	pMF->SetPrdVersion(strTmp);

	
	return TRUE;
}

BOOL CMainPage::LoadConfig(LPCTSTR pFileName)
{
//ini first
	ASSERT(NULL != pFileName);
    if(NULL == pFileName)
    {
        return FALSE;
    }   
    m_strIniFile = pFileName;

    // Get Default Baudrates
    _TCHAR szBaudSection[MAX_PATH];
    memset(szBaudSection,0,MAX_PATH);
	::GetPrivateProfileString(g_sz_SEC_GUI,g_sz_KEY_BRS,g_sz_BR_DEFAULT,szBaudSection,MAX_PATH,pFileName);

	CString strBaudRate;
	strBaudRate = szBaudSection;
	if(!strBaudRate.IsEmpty())
    {
		m_arrBaudRateConfig.RemoveAll();
		int     nLen   = strBaudRate.GetLength();
		LPTSTR  lpBuf  = strBaudRate.GetBuffer(nLen);
		LPTSTR  lpFind = _tcschr(lpBuf, _T(','));
		while(lpFind != NULL)
		{
			*lpFind = _T('\0');

			m_arrBaudRateConfig.Add(lpBuf);
			lpBuf = lpFind + 1;
			lpFind = _tcschr(lpBuf, _T(','));
		}
		m_arrBaudRateConfig.Add(lpBuf);
		strBaudRate.ReleaseBuffer();
    }

    // Get baudrate
    m_nBaudRate = ::GetPrivateProfileInt(g_sz_SP,g_sz_BR,115200,pFileName);
    m_nComPort = ::GetPrivateProfileInt( g_sz_SP, g_sz_PORT, 0, pFileName );

#ifdef _SPUPGRADE
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 0, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 0, pFileName );
#else
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 1, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 1, pFileName );
#endif

#ifdef _DOWNLOAD_FOR_PRODUCTION
	m_bCanSel = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_SEL, 0, pFileName );
	m_bCanEdit = ::GetPrivateProfileInt( g_sz_SEC_GUI, g_sz_KEY_EDT, 0, pFileName );
#endif

	m_wLangNVItemID = (WORD)::GetPrivateProfileInt( g_sz_SEC_NV, g_sz_KEY_LNII, NV_MULTI_LANG_ID, pFileName );

	m_bEnableChipDspMap = ::GetPrivateProfileInt( g_sz_SEC_CHIPDSPMAP, g_sz_KEY_CDME, FALSE, pFileName );
	
	BOOL bFDL = FALSE;
	if(m_arrFileName.GetSize()>0 )
	{
		if(!m_arrFileName.GetAt(0).IsEmpty() && m_arrAllFileName.GetAt(0).Compare(FILE_OMIT) != 0)
			bFDL = TRUE;
	}
	if(!m_strCurProduct.IsEmpty() && bFDL  )
		m_bInit = TRUE;

	CString strXMLConfig = GetXmlFile(pFileName);
	if(!LoadAllProduct(strXMLConfig))
		return FALSE;

	m_bTmpOmaDM = m_bOmaDM;
	m_bTmpPreload = m_bPreload;
	m_bTmpKernelImg2 = m_bKernelImg2;
	m_bTmpRomDisk = m_bRomDisk;

	InitCaliPage(m_pTmpProductInfo);
	InitNandPage();
	InitMultiLangPage();

    return TRUE;
}

HBRUSH CMainPage::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
	HBRUSH hbr = CPropertyPage::OnCtlColor(pDC, pWnd, nCtlColor);
	
	// TODO: Change any attributes of the DC here

	if(pWnd->GetDlgCtrlID() == IDC_EDT_PRD_VERSION)
	{
		pDC->SetTextColor(RGB(0,128,64));
 	}
	
	// TODO: Return a different brush if the default is not desired
	return hbr;
}

//return FALSE always, this is for user clicking packet button repeatly
BOOL CMainPage::DoPacket() 
{
    //检查是否选择了文件，并且选择的文件应该输入文件路径的，必须已输入文件路径
	BOOL bNvFileSelected = FALSE;
	BOOL bFlashSelected = FALSE;

	BOOL bUDiskImgSelected = FALSE;	
	CString strUDiskImgFile;

	BOOL bDspImgSelected = FALSE;
	CString strDspImgFile;

	int nItemCount = m_lstProductInfo.GetItemCount();
	if(nItemCount == 0)
	{
		AfxMessageBox(_T("Please select files to download!"));
		CMD_PAC_EXIT;
		return FALSE;		
	}

	CString strTmp = _T("");
    int i = 0;
	int nRealDownFile = 0;
	int nAllowOmit = 0;
	for(i = 0;i<nItemCount;i++)
	{
		CString strFileID = m_pTmpProductInfo->pFileInfoArr[i].szID;
		DWORD dwItemData = m_lstProductInfo.GetItemData(i);	
		if(m_lstProductInfo.GetCheck(i) )
		{
			if(LOWORD(dwItemData)!=0)
			{
				CString strDLFile = m_lstProductInfo.GetItemText(i,1);
				if(strDLFile.IsEmpty())
				{
					AfxMessageBox(IDS_ERR_FILE_EMPTY);
					CMD_PAC_EXIT;
					return FALSE;
				}
				else
				{
					if(!CheckFileValidate(strDLFile))
					{
						strTmp += strDLFile;
						strTmp += _T("\n");						
					}
				}
				//检查是否选择了NV文件				
				if(strFileID.CompareNoCase(_T("NV")) == 0)
				{
					bNvFileSelected = TRUE;
				}
				else if(strFileID.CompareNoCase(_T("UDISK_IMG")) == 0)
				{
					bUDiskImgSelected = TRUE;
					strUDiskImgFile = m_lstProductInfo.GetItemText(i,1);
				}
				else if(strFileID.CompareNoCase(_T("DSPCode")) == 0)
				{
					bDspImgSelected = TRUE;
					strDspImgFile = m_lstProductInfo.GetItemText(i,1);
				}
					
			}
			else
			{
				//检查是否选择了擦除Flash
				if(strFileID.CompareNoCase(_T("FLASH")) == 0)
				{
					bFlashSelected = TRUE;
				}		
			}

			nRealDownFile++;			
		}
		else
		{
			if(DI_IS_GRAY(dwItemData) || DI_IS_OMIT(dwItemData))
			{
				nAllowOmit++;
			}
		}
	
	}
	if(!strTmp.IsEmpty())
	{
		CString strError;
		strError.Format(IDS_ERR_FILES_NOT_EXIST,strTmp);
		AfxMessageBox(strError);
		CMD_PAC_EXIT;
		return FALSE;
	}

    BOOL bAllFileDown = TRUE;
	if( nAllowOmit != ( nItemCount - nRealDownFile) )
	{
		bAllFileDown = FALSE;
	}

    //检查NandFlash分区策略
	BOOL bNand = m_pTmpProductInfo->dwFlashType;
	
	int nRepStrategy = m_pNandPage->m_nRepartitionFlag;

	BOOL bRepartition = FALSE;
	if(nRepStrategy == REPAR_STRATEGY_ALWAYS || nRepStrategy == REPAR_STRATEGY_DO)
	{
		bRepartition = TRUE;
	}
#if 0
	//not select flash
	if(!bFlashSelected)
	{
		if(AfxMessageBox(_T("You have not selected FLASH to earase flash.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}

	//not select NV
	if(!bNvFileSelected)
	{
		if(AfxMessageBox(_T("You have not selected NV file.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}


    //检查选择了备份NV
	m_pCaliPage->m_lstBackup.UpdateTemp();
	BOOL bBackupNV = TRUE;
	bBackupNV = m_pCaliPage->m_lstBackup.m_bTempBackNV;
	//如果选择了NV文件，但没有选择备份任何NV项
	if(!bBackupNV && bNvFileSelected)
	{
		if(AfxMessageBox(_T("You have not selected any NV item to backup.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}	

	//如果没有选择所有文件
	if(!bAllFileDown)
	{
		if(AfxMessageBox(_T("You have not selected all files.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}
	
	if(bNand && bRepartition && !bAllFileDown)
	{
		if(AfxMessageBox(_T("You have selected repartition,\nbut you have not selected all files to download.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}
	
	if(bNand && bRepartition && !bBackupNV && bNvFileSelected)
	{
		if(AfxMessageBox(_T("You have selected repartition,\nbut you have not selected any NV item to backup.\nIf continue?"),MB_YESNO) == IDNO)
			return FALSE;
	}

	if(bNand && bRepartition && bBackupNV && !bNvFileSelected)
	{
		if(AfxMessageBox(_T("You have selected backup nv,\nbut you have not input the NV file.\nIf continue?"),MB_YESNO) == IDNO)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}
	}
#endif
	CString strPrdName = m_strTempProduct;
	CString strPrdAlias = m_strTempProduct;
	CString strPacPath = g_theApp.m_strPacPath;
	CString strPrdVersion = g_theApp.m_strPrdVersion;
	if(strPrdName.Find(_T("PAC_")) == 0)
	{
		strPrdName.Delete(0,4);
	}

	if(!g_theApp.m_bCMDPackage)
	{		
		CDlgPacketSetting dlg;
		dlg.m_strPrdName = strPrdName;
		dlg.m_strPrdAlias = strPrdName;

		if(dlg.DoModal() == IDCANCEL)
			return FALSE;

		strPrdName = dlg.m_strPrdName;
		strPrdAlias = dlg.m_strPrdAlias;
		strPacPath = dlg.m_strPath;
		strPrdVersion = dlg.m_strVersion;
	}

	int nFileNum = nItemCount;

	CStringArray agUDiskFiles;
	int nUDiskFiles = 0;
	if(bUDiskImgSelected)
	{
		nUDiskFiles = GetUDiskFiles(strUDiskImgFile,agUDiskFiles);
		nFileNum += nUDiskFiles;
	}

	CStringArray agDspFiles;
	int nDspFiles = 0;
	if(bDspImgSelected)
	{
		nDspFiles = GetDspFiles(strDspImgFile,agDspFiles);
		if(nDspFiles == -1)
		{
			CMD_PAC_EXIT;
			return FALSE;
		}

		nFileNum += nDspFiles;
	}


	FILE_T * paFile = new FILE_T[nFileNum];
	FILE_T * pFT = NULL;
	for(i=0;i<nItemCount;i++)
	{
        pFT = paFile + i;
		pFT->nCheckFlag = m_lstProductInfo.GetCheck(i);
		CString strFileName = m_lstProductInfo.GetItemText(i,1);
		CString strFileID = m_pTmpProductInfo->pFileInfoArr[i].szID;
		_tcscpy(pFT->szFileID,strFileID);
		if(pFT->nCheckFlag)
		{
			_tcscpy(pFT->szFileName,strFileName);
		}		
		DWORD dwItemData = m_lstProductInfo.GetItemData(i);
		pFT->nFileFlag = LOWORD(dwItemData);
		if(DI_IS_GRAY(dwItemData) || DI_IS_OMIT(dwItemData))
		{
			pFT->dwCanOmitFlag = 1;
		}
	}

	for(i=0;i<nUDiskFiles;i++)
	{
		pFT = paFile + nItemCount + i;
		pFT->nCheckFlag = 1;
		_tcscpy(pFT->szFileName,agUDiskFiles.GetAt(i));
	}
	for(i=0;i<nDspFiles;i++)
	{
		pFT = paFile + nItemCount + nUDiskFiles+ i;
		pFT->nCheckFlag = 1;
		_tcscpy(pFT->szFileName,agDspFiles.GetAt(i));
	}

	CBinPack bp;
	if(!bp.Open(strPacPath))
	{
		delete []paFile;
		CMD_PAC_EXIT;
		return FALSE;
	}
	CString strCfgFile;
	m_mapPrdCfg.Lookup(m_strTempProduct,strCfgFile);

	BIN_PACKET_HEADER_T bph;
	_tcscpy(bph.szPrdName,strPrdName);
    _tcscpy(bph.szPrdVersion,strPrdVersion);

	strPrdAlias.TrimLeft();
	strPrdAlias.TrimRight();
	if(!strPrdAlias.IsEmpty())
	{
		_tcscpy(bph.szPrdAlias,strPrdAlias);
	}

	bph.nFileCount = nFileNum;
	bph.dwFlashType = m_pTmpProductInfo->dwFlashType;
	bph.dwMode = m_pTmpProductInfo->dwMode;
	bph.dwNandStrategy = m_pNandPage->m_nRepartitionFlag;
	bph.dwNandPageType = m_pNandPage->m_nFlashType;

	BOOL bBackupNv = m_pCaliPage->m_lstBackup.m_bTempBackNV;
	int  nNBICount = m_pCaliPage->m_lstBackup.m_nTempNvBkpItmCount;

	bph.dwIsNvBackup = (DWORD)bBackupNv;

	bph.dwOmaDmProductFlag = m_pTmpProductInfo->dwOmaDMFlag;
	bph.dwIsOmaDM = m_bTmpOmaDM;
	bph.dwIsPreload = m_bTmpPreload;

	_X_NV_BACKUP_ITEM_T *pnvi = NULL;
	if(nNBICount != 0)
	{
		pnvi = new _X_NV_BACKUP_ITEM_T[m_pCaliPage->m_lstBackup.m_nTempNvBkpItmCount];

	    memcpy(pnvi,m_pCaliPage->m_lstBackup.m_pTempNvBkpItmArray,sizeof(_X_NV_BACKUP_ITEM_T)*nNBICount);
	}
	
	BOOL bOK = bp.Packet(&bph,strCfgFile,paFile,TRUE,pnvi,nNBICount,0);
    
	if(pnvi != NULL)
	   delete [] pnvi;

	bp.Close();

	if(g_theApp.m_bCMDPackage)
	{
		GetParent()->PostMessage(WM_COMMAND, IDCANCEL);
		AfxGetMainWnd()->PostMessage(WM_CLOSE);
		return FALSE;
	}
	else
	{
		if(bOK)
			AfxMessageBox(_T("Packeting complete!"));
		else
			AfxMessageBox(_T("Packeting failed!"));
	}


	return FALSE;
}
BOOL CMainPage::DeepCopyProductInfo( PPRODUCT_INFO_T pDst, const PPRODUCT_INFO_T pSrc)
{
	_ASSERTE(pDst != NULL && pSrc != NULL);
	memcpy(pDst,pSrc,sizeof(PRODUCT_INFO_T));

	pDst->pFileInfoArr = NULL;
	if(pDst->dwFileCount!=0)
	{
		pDst->pFileInfoArr = new FILE_INFO_T[pDst->dwFileCount];
		if(pDst->pFileInfoArr == NULL)
		{
			return FALSE;
		}

		memcpy(pDst->pFileInfoArr,pSrc->pFileInfoArr,sizeof(FILE_INFO_T)*(pDst->dwFileCount));
	}
	pDst->paNvBackupItem = NULL;
	if(pDst->dwNvBackupItemCount != 0)
	{
		pDst->paNvBackupItem = new NV_BACKUP_ITEM_T[pDst->dwNvBackupItemCount];
		if(pDst->paNvBackupItem == NULL)
		{
			if(pDst->pFileInfoArr != NULL)
			{
				delete [] pDst->pFileInfoArr;
				pDst->pFileInfoArr = NULL;
			}
			return FALSE;
		}
		memcpy(pDst->paNvBackupItem,pSrc->paNvBackupItem,sizeof(NV_BACKUP_ITEM_T)*(pDst->dwNvBackupItemCount));
	}

	return TRUE;
}
void CMainPage::ClearProdInfoVector()
{
	UINT i=0;
	for(i=0;i<m_vctProductInfo.size();i++)
	{
		if(((PPRODUCT_INFO_T)m_vctProductInfo[i])->pFileInfoArr != NULL)
		{
			delete [] ((PPRODUCT_INFO_T)m_vctProductInfo[i])->pFileInfoArr;
			((PPRODUCT_INFO_T)m_vctProductInfo[i])->pFileInfoArr = NULL;
		}
		if(((PPRODUCT_INFO_T)m_vctProductInfo[i])->paNvBackupItem != NULL)
		{
			delete [] ((PPRODUCT_INFO_T)m_vctProductInfo[i])->paNvBackupItem;
			((PPRODUCT_INFO_T)m_vctProductInfo[i])->paNvBackupItem = NULL;
		}
		delete m_vctProductInfo[i];
	}
	m_vctProductInfo.clear();
}
BOOL CMainPage::CheckFileValidate(LPCTSTR lpszFile)
{
	if(lpszFile == NULL)
		return FALSE;

	BOOL bOK = FALSE;

	CFileFind finder;
	if(finder.FindFile(lpszFile))
	{
			HANDLE hFile = CreateFile(lpszFile,
							 GENERIC_READ, 
							 FILE_SHARE_READ,
							 NULL, 
							 OPEN_EXISTING, 
							 FILE_ATTRIBUTE_NORMAL, 
							 NULL);

		   if (hFile != INVALID_HANDLE_VALUE)	
		   {
			   CFile file((int)hFile);
			   if(file.GetLength()!=0)
			   {
					bOK = TRUE;
			   }
			   file.Close();
			   //CloseHandle(hFile);
		   }
	}

	return bOK;
}

BOOL CMainPage::FindLangNVItem(LPCTSTR lpszFilePath,CUIntArray &agLangFlag, FILETIME * pLastWriteTime)
{
	if(lpszFilePath == NULL || m_wLangNVItemID == 0xFFFF)
		return FALSE;

	CFileFind finder;
	if(!finder.FindFile(lpszFilePath))
	{
		return FALSE;
	}

	agLangFlag.RemoveAll();

	BOOL bRlt = FALSE;

	HANDLE hFile = INVALID_HANDLE_VALUE;
	hFile = ::CreateFile(lpszFilePath,
		                 GENERIC_READ,
						 FILE_SHARE_READ,
						 NULL,
						 OPEN_EXISTING,
						 FILE_ATTRIBUTE_NORMAL,
						 NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		return FALSE;
	}

	if(pLastWriteTime != NULL)
	{
		::GetFileTime(hFile,NULL,NULL,pLastWriteTime);
	}

	DWORD dwSize = GetFileSize(hFile,NULL);

	if(dwSize == 0 || dwSize == 0xFFFFFFFF)
	{
		return FALSE;
	}

	BYTE *pBuf = new BYTE[dwSize];

	DWORD dwRealRead =  0;
	ReadFile(hFile,pBuf,dwSize,&dwRealRead,NULL);
	DWORD dwOffset=0;
	DWORD dwLength=0;
	if(FindNVOffset(m_wLangNVItemID,pBuf,dwSize,dwOffset,dwLength) && dwLength == sizeof(NV_MULTI_LANGUE_CFG))
	{
		bRlt = TRUE;
		NV_MULTI_LANGUE_CFG *pObj= (NV_MULTI_LANGUE_CFG *)(pBuf+dwOffset);
	
		for(int i=0;i< NV_MAX_LANG_NUM;i++)
		{
			agLangFlag.Add((UINT)pObj->flag[i]);
		}
	}	

	CloseHandle(hFile);
	
	delete [] pBuf;

	return bRlt;

}

int CMainPage::GetFileInfo(LPCTSTR lpszFileID, LPDWORD ppFileInfo, BOOL bWnd /*= FALSE*/)
{
	if(lpszFileID == NULL)
	{
		return -1;
	}

	int nCount = 0;
	PFILE_INFO_T pFileInfo = NULL;
	if(!bWnd)
	{
		nCount = m_pCurProductInfo->dwFileCount;
		pFileInfo= m_pCurProductInfo->pFileInfoArr;
	}
	else
	{
		nCount = m_pTmpProductInfo->dwFileCount;
		pFileInfo= m_pTmpProductInfo->pFileInfoArr;
	}

	int i=0;
	CString strID;
	for(i = 0;i<nCount;i++)
	{
		strID = (pFileInfo+i)->szID;
		if( strID.CompareNoCase(lpszFileID)==0)
		{
			if(ppFileInfo!= NULL)
			    *ppFileInfo = (DWORD)(pFileInfo+i);
			break;
		}
	}
	
	if(i>=nCount)
		return -1;
	else
		return i;
}
/*
BOOL CMainPage::IsDMFdl2(LPCTSTR lpszFilePath)
{
	if(lpszFilePath == NULL || _tcslen(lpszFilePath) == 0)
	{
		return TRUE;
	}

	CFileFind finder;
	if(!finder.FindFile(lpszFilePath))
		return FALSE;

	CString strError;

	CFile file;
    CFileException fe;
    BOOL bRet = file.Open( lpszFilePath,CFile::modeRead|CFile::shareDenyWrite,&fe );

    if( !bRet )
    {
        // Can not open file
        LPTSTR p = strError.GetBuffer( _MAX_PATH );
        fe.GetErrorMessage( p,_MAX_PATH );
        strError.ReleaseBuffer();
		CString strTmp;
		strTmp.Format(_T("Can not open file [%s]!\n(%s)"),lpszFilePath,strError);
		AfxMessageBox(strTmp);
        return bRet;
    }

    LPBYTE lpContent = NULL;
    int nLen = 0;

    try
    {
        nLen = file.GetLength();
        lpContent = new BYTE[nLen];
        file.Read( lpContent,nLen );
    }
    catch( CFileException fe )
    {
        LPTSTR p = strError.GetBuffer( _MAX_PATH );
        fe.GetErrorMessage( p,_MAX_PATH );
        strError.ReleaseBuffer();
		CString strTmp;
		strTmp.Format(_T("Can not open file [%s]!\n(%s)"),lpszFilePath,strError);
		AfxMessageBox(strTmp);
        delete lpContent;
        return FALSE;
    }
   
    char szCon[] = "#$DEVICE_MANAGER$#";
    BYTE* lpPos = std::search( lpContent,lpContent + nLen,szCon,szCon + strlen( szCon ) - 1 );
    if( lpPos == lpContent + nLen )
    {
        // not find the version string
        delete []lpContent;
        return FALSE;
    }
	else
	{
		delete []lpContent;
    
		return TRUE;
	}   

}*/

BOOL CMainPage::GetFdl2Flag(LPCTSTR lpszFilePath,UINT nType)
{
	if(lpszFilePath == NULL || _tcslen(lpszFilePath) == 0)
	{
		return TRUE;
	}

	CFileFind finder;
	if(!finder.FindFile(lpszFilePath))
		return FALSE;

	CString strError;

	CFile file;
    CFileException fe;
    BOOL bRet = file.Open( lpszFilePath,CFile::modeRead|CFile::shareDenyWrite,&fe );

    if( !bRet )
    {
        // Can not open file
        LPTSTR p = strError.GetBuffer( _MAX_PATH );
        fe.GetErrorMessage( p,_MAX_PATH );
        strError.ReleaseBuffer();
		CString strTmp;
		strTmp.Format(_T("Can not open file [%s]!\n(%s)"),lpszFilePath,strError);
		AfxMessageBox(strTmp);
        return bRet;
    }

    LPBYTE lpContent = NULL;
    int nLen = 0;

    try
    {
        nLen = file.GetLength();
        lpContent = new BYTE[nLen];
        file.Read( lpContent,nLen );
    }
    catch( CFileException fe )
    {
        LPTSTR p = strError.GetBuffer( _MAX_PATH );
        fe.GetErrorMessage( p,_MAX_PATH );
        strError.ReleaseBuffer();
		CString strTmp;
		strTmp.Format(_T("Can not open file [%s]!\n(%s)"),lpszFilePath,strError);
		AfxMessageBox(strTmp);
        delete lpContent;
        return FALSE;
    }
   
    const char szOmadm[] = "#$DEVICE_MANAGER$#";
	const char szPreload[] = "#*PRELOADSUPPORT*#";
	const char szKernelImg2[]="#*DEMANDPAGING*#";
	const char szRomDisk[]= "#*USBCOMAUTORUN*#";

    BYTE* lpPos = NULL;
	if(nType == FDL2F_OMADM)
	{
		lpPos = std::search( lpContent,lpContent + nLen,szOmadm,szOmadm + strlen( szOmadm ) - 1 );
	}
	else if(nType == FDL2F_PRELOAD)
	{
		lpPos = std::search( lpContent,lpContent + nLen,szPreload,szPreload + strlen( szPreload ) - 1 );
	}
	else if(nType == FDL2F_KERNELIMG2)
	{
		lpPos = std::search( lpContent,lpContent + nLen,szKernelImg2,szKernelImg2 + strlen( szKernelImg2 ) - 1 );
	}
	else if(nType == FDL2F_ROMDISK)
	{
		lpPos = std::search( lpContent,lpContent + nLen,szRomDisk,szRomDisk + strlen( szRomDisk ) - 1 );
	}
	else
	{
		delete []lpContent;
		return FALSE;
	}

    if( lpPos == lpContent + nLen )
    {
        // not find the version string
        delete []lpContent;
        return FALSE;
    }
	else
	{
		delete []lpContent;    
		return TRUE;
	}   
}

void CMainPage::OnRclickLstProductInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(!m_bCanEdit)
	{
		*pResult = 0;
		return;
	}
	
	LPNMITEMACTIVATE pnia = (LPNMITEMACTIVATE)pNMHDR;


	int nItem = pnia->iItem;
	int nSubItem = pnia->iSubItem;
	if(nItem == -1 || nSubItem != 1)
		return;
	//LOWORD is file flag
	//HIWORD is gray flag
	if(LOWORD(m_lstProductInfo.GetItemData(nItem)) == 0)
		return;
	
	static _TCHAR BASED_CODE szFilter[] = _T("Binary Files (*.bin)|*.bin|All Files(*.*)|*.*||");
    CString strFile=_T("");	
    CFileDialog dlg(TRUE, NULL, strFile, OFN_NOCHANGEDIR |OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, szFilter, NULL);
	
	if(dlg.DoModal() == IDOK)
    {
		CString strText = dlg.GetPathName();
		m_lstProductInfo.SetItemText(nItem,nSubItem,strText);
		if(m_pTmpProductInfo->dwOmaDMFlag != 0)
		{
			
			CString fileID = m_pTmpProductInfo->pFileInfoArr[nItem].szID;
			if(fileID.CompareNoCase(_T("FDL2"))== 0)
			{
				m_bTmpOmaDM= GetFdl2Flag(strText,FDL2F_OMADM);
				m_bTmpPreload= GetFdl2Flag(strText,FDL2F_PRELOAD);	
				m_bTmpKernelImg2= GetFdl2Flag(strText,FDL2F_KERNELIMG2);
				m_bTmpRomDisk = GetFdl2Flag(strText,FDL2F_ROMDISK);
				
				for(int i= 0; i< m_lstProductInfo.GetItemCount();i++)
				{
					//fileID =  m_lstProductInfo.GetItemText(i,0);
					fileID =  m_pTmpProductInfo->pFileInfoArr[i].szID;
					if(fileID.CompareNoCase(g_szUA)==0 || fileID.CompareNoCase(g_szEDU)==0 )
					{
						m_lstProductInfo.SetCheck(i,m_bTmpOmaDM);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpOmaDM)
						{						
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{							
							dwData = DI_UNSET_GRAY(dwData);
						}
						
						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}					
					else if(fileID.CompareNoCase(g_szPreload)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpPreload);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpPreload)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}
						
						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
					else if(fileID.CompareNoCase(g_szKernelImg2)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpKernelImg2);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpKernelImg2)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}
						
						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
					else if(fileID.CompareNoCase(g_szRomDisk)==0)
					{
						m_lstProductInfo.SetCheck(i,m_bTmpRomDisk);
						DWORD dwData = m_lstProductInfo.GetItemData(i);
						if(!m_bTmpRomDisk)
						{
							dwData = DI_SET_GRAY(dwData);
						}
						else
						{
							dwData = DI_UNSET_GRAY(dwData);
						}
						
						m_lstProductInfo.SetItemData(i,dwData);
						GetDlgItem(IDC_CHK_ALL)->EnableWindow(m_bTmpOmaDM && m_bTmpPreload && m_bTmpKernelImg2 && m_bTmpRomDisk);
					}
				}				
			}
		}
		
    }

	*pResult = 0;
}

void CMainPage::OnClickLstProductInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	LPNMITEMACTIVATE pnia = (LPNMITEMACTIVATE)pNMHDR;

	int nItem = pnia->iItem;
	int nSubItem = pnia->iSubItem;
	if(nItem == -1 || nSubItem != 1)
	{
		if(m_pTmpProductInfo != NULL)
		{
			m_stcProdComment.SetText(m_pTmpProductInfo->szComment);
		}
		return;
	}

	CString strFileDescript=_T("");
	CString strTips;
	if(m_pTmpProductInfo!= NULL)
	{
		if(_tcslen(m_pTmpProductInfo->pFileInfoArr[nItem].szFileDescript)>0)
		{
			strFileDescript.Format(_T("Note: %s"),m_pTmpProductInfo->pFileInfoArr[nItem].szFileDescript);
		}
	}

	CString strFile = m_lstProductInfo.GetItemText(nItem,nSubItem);
	if(LOWORD(m_lstProductInfo.GetItemData(nItem)) == 0 || strFile.IsEmpty())
	{
		strTips = strFileDescript;
		m_stcProdComment.SetText(strTips);
		
	}
	else
	{
		CFileFind finder;
		if(finder.FindFile(strFile))
		{
			finder.FindNextFile();
			CTime lwt;
			finder.GetLastWriteTime(lwt);

// 			if(strFile.GetLength()>49)
// 			{
// 				strFile.Insert(48,_T("\n"));
// 			}
	

			strTips.Format(_T("Size: %-8d [0x%08X] Modify Time:%04d-%02d-%02d %02d:%02d:%02d\n%s"),		
					      finder.GetLength(),
						  finder.GetLength(),
						  lwt.GetYear(),
						  lwt.GetMonth(),
						  lwt.GetDay(),
						  lwt.GetHour(),
						  lwt.GetMinute(),
						  lwt.GetSecond(),
						  strFileDescript);

						  
		}
		else
		{
// 			if(strFile.GetLength()>49)
// 			{
// 				strFile.Insert(48,_T("\n"));
// 			}

			strTips.Format(_T("File Not Found!\n%s"),strFileDescript);

		}
		m_stcProdComment.SetText(strTips);

	}	
	*pResult = 0;
}

int CMainPage::GetUDiskFiles(LPCTSTR lpszBaseUDiskFile, CStringArray &agFiles)
{
	agFiles.RemoveAll();

	CString strUDiskImgFile = lpszBaseUDiskFile;
	int nFileNameLen = UDSIK_IMG_NAME_LEN;
	CString strDir = strUDiskImgFile;
	
	int nFind = strDir.ReverseFind(_T('\\'));
	strDir = strDir.Left(nFind);

	CString strFind = strDir + _T("\\udisk_img_*.bin");	

	WIN32_FIND_DATA wfd = { 0 };
	HANDLE hFind = ::FindFirstFile( strFind, &wfd );
	BOOL bFind = TRUE;
	while( INVALID_HANDLE_VALUE != hFind  && bFind)
	{
		CString strFileName =((CString) (wfd.cFileName)).Left(((CString) (wfd.cFileName)).GetLength() - 4);
		if( strFileName.GetLength() == nFileNameLen)
		{
			CString strFile;
			strFile.Format(_T("%s\\%s"),strDir,wfd.cFileName);
			if(strFile.CompareNoCase(strUDiskImgFile) != 0 )
			{
				agFiles.Add(strFile);
			}
		}
		bFind = ::FindNextFile(hFind, &wfd);			
	}
	if(INVALID_HANDLE_VALUE != hFind)
	{
		::FindClose(hFind);	
	}

	return agFiles.GetSize();
}

int  CMainPage::GetDspFiles(LPCTSTR lpszBaseDspFile, CStringArray &agFiles)
{
	agFiles.RemoveAll();
	if(!m_bEnableChipDspMap)
	{
		// need not chip-dsp map
		return 0;
	}
	
	_TCHAR szConfigPath[_MAX_PATH]={0};
	::GetModuleFileName(g_theApp.m_hInstance,szConfigPath,_MAX_PATH);
	LPTSTR pResult = _tcsrchr(szConfigPath,_T('\\'));
	*pResult = 0;
	_tcscat(szConfigPath,_T("\\BMFileType.ini"));
	
	_TCHAR szKeyValue[ MAX_BUF_SIZE ]={0}; 
	DWORD dwSize = GetPrivateProfileSection( _T("ChipDSPMap"), szKeyValue, MAX_BUF_SIZE, szConfigPath );
	if(dwSize == 0)
	{
		AfxMessageBox(_T("Not found ChipID-DSPName map setting in BMFileType.ini!"));
		return -1;
	}
	CStringArray arrKeyData;    
	UINT nFileCount = (UINT)EnumKeys(szKeyValue,&arrKeyData);
	if(nFileCount == 0)
	{
		AfxMessageBox(_T("Not found ChipID-DSPName map setting in BMFileType.ini!"));
		return -1;
	}
	
	CString strErrMsg =_T("");
	
	CString strDspFile = lpszBaseDspFile;
	CString strDir = strDspFile;	
	int nFind = strDir.ReverseFind(_T('\\'));
	strDir = strDir.Left(nFind);	
	CFileFind finder;
	for(UINT i= 0; i< nFileCount; i++)
	{				
		CString strFile;
		strFile.Format(_T("%s\\%s"),strDir,arrKeyData[2*i+1]);
		if(!finder.FindFile(strFile))
		{
			strErrMsg += strFile;
			strErrMsg += _T("\r\n");
			continue;
		}
		else
		{
			if(strFile.CompareNoCase(strDspFile)!= 0)
			{
				agFiles.Add(strFile);
			}		
		}
	}	
	if(!strErrMsg.IsEmpty())
	{
		strErrMsg.Insert(0,_T("Not found bellow DSP file:\r\n"));
		strErrMsg += _T("\r\nPlease check BMFileType.ini, [ChipDspMap]!");
		AfxMessageBox(strErrMsg);
		return -1;
	}	
	return agFiles.GetSize();
}
