// SettingsSheet.cpp : implementation file
//

#include "stdafx.h"
#include "dloader.h"
#include "SettingsSheet.h"
#include "MainFrm.h"
#include <afxpriv.h>

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

#define WM_RESIZEPAGE (WM_APP+1)

enum { CDF_CENTER, CDF_TOPLEFT, CDF_NONE };

BOOL g_bInitSheet = FALSE;

void ChangeDialogFont(CWnd* pWnd, CFont* pFont, int nFlag)
{
    CRect windowRect;
    
    // grab old and new text metrics
    TEXTMETRIC tmOld, tmNew;
    CDC * pDC = pWnd->GetDC();
    CFont * pSavedFont = pDC->SelectObject(pWnd->GetFont());
    pDC->GetTextMetrics(&tmOld);
    pDC->SelectObject(pFont);
    pDC->GetTextMetrics(&tmNew);
    pDC->SelectObject(pSavedFont);
    pWnd->ReleaseDC(pDC);
    
    long oldHeight = tmOld.tmHeight+tmOld.tmExternalLeading;
    long newHeight = tmNew.tmHeight+tmNew.tmExternalLeading;
    
    if (nFlag != CDF_NONE)
    {
        // calculate new dialog window rectangle
        CRect clientRect, newClientRect, newWindowRect;
        
        pWnd->GetWindowRect(windowRect);
        pWnd->GetClientRect(clientRect);
        long xDiff = windowRect.Width() - clientRect.Width();
        long yDiff = windowRect.Height() - clientRect.Height();
        
        newClientRect.left = newClientRect.top = 0;
        newClientRect.right = clientRect.right * tmNew.tmAveCharWidth / tmOld.tmAveCharWidth;
        newClientRect.bottom = clientRect.bottom * newHeight / oldHeight;
        
        if (nFlag == CDF_TOPLEFT) // resize with origin at top/left of window
        {
            newWindowRect.left = windowRect.left;
            newWindowRect.top = windowRect.top;
            newWindowRect.right = windowRect.left + newClientRect.right + xDiff;
            newWindowRect.bottom = windowRect.top + newClientRect.bottom + yDiff;
        }
        else if (nFlag == CDF_CENTER) // resize with origin at center of window
        {
            newWindowRect.left = windowRect.left - 
                (newClientRect.right - clientRect.right)/2;
            newWindowRect.top = windowRect.top -
                (newClientRect.bottom - clientRect.bottom)/2;
            newWindowRect.right = newWindowRect.left + newClientRect.right + xDiff;
            newWindowRect.bottom = newWindowRect.top + newClientRect.bottom + yDiff;
        }
        pWnd->MoveWindow(newWindowRect);
    }
    
    pWnd->SetFont(pFont);
    
    // iterate through and move all child windows and change their font.
    CWnd* pChildWnd = pWnd->GetWindow(GW_CHILD);
    
    while (pChildWnd)
    {
        pChildWnd->SetFont(pFont);
        pChildWnd->GetWindowRect(windowRect);
        
        CString strClass;
        ::GetClassName(pChildWnd->m_hWnd, strClass.GetBufferSetLength(32), 31);
        strClass.MakeUpper();
        if(strClass==_T("COMBOBOX"))
        {
            CRect rect;
            pChildWnd->SendMessage(CB_GETDROPPEDCONTROLRECT,0,(LPARAM) &rect);
            windowRect.right = rect.right;
            windowRect.bottom = rect.bottom;
        }
        
        pWnd->ScreenToClient(windowRect);
        windowRect.left = windowRect.left * tmNew.tmAveCharWidth / tmOld.tmAveCharWidth;
        windowRect.right = windowRect.right * tmNew.tmAveCharWidth / tmOld.tmAveCharWidth;
        windowRect.top = windowRect.top * newHeight / oldHeight;
        windowRect.bottom = windowRect.bottom * newHeight / oldHeight;
        pChildWnd->MoveWindow(windowRect);
        
        pChildWnd = pChildWnd->GetWindow(GW_HWNDNEXT);
    }
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsSheet

IMPLEMENT_DYNAMIC(CSettingsSheet, CPropertySheet)

CSettingsSheet::CSettingsSheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage)
	:CPropertySheet(nIDCaption, pParentWnd, iSelectPage)
{
	memset(&m_rctPage,0,sizeof(m_rctPage));
	m_pageMain.SetCaliPage(&m_pageCalibration);
	m_pageMain.SetNandPage(&m_pageNandFlash);
	m_pageMain.SetMultiLangPage(&m_pageMultiLang);
	AddPage(&m_pageMain);
#if defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION)
	if(g_theApp.m_bShowOtherPage)
	{
		AddPage( &m_pageNandFlash );
		AddPage( &m_pageCalibration );
	}
#else
	/* @hongliang.xin 2009-6-29 must show other page for DloaderR, 
	   otherwise, the Calibration Page will assert for debug */
	AddPage( &m_pageNandFlash );
	AddPage( &m_pageCalibration );
	AddPage( &m_pageFlashOpt );
#endif

	AddPage(&m_pageMultiLang);

//  AddPage(&m_pageMode);	

}

CSettingsSheet::CSettingsSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
	:CPropertySheet(pszCaption, pParentWnd, iSelectPage)
{
	memset(&m_rctPage,0,sizeof(m_rctPage));
	m_pageMain.SetCaliPage(&m_pageCalibration);
	m_pageMain.SetNandPage(&m_pageNandFlash);
	m_pageMain.SetMultiLangPage(&m_pageMultiLang);
	AddPage(&m_pageMain);

#if defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION)
	if(g_theApp.m_bShowOtherPage)
	{
		AddPage( &m_pageNandFlash );
		AddPage( &m_pageCalibration );
	}
#else
	/* @hongliang.xin 2009-6-29 must show other page for DloaderR, 
	   otherwise, the Calibration Page will assert for debug */
	AddPage( &m_pageNandFlash );
	AddPage( &m_pageCalibration );
#endif

	AddPage(&m_pageMultiLang);
//    AddPage(&m_pageMode);

}

CSettingsSheet::~CSettingsSheet()
{
    if (m_fntPage.m_hObject)
        VERIFY (m_fntPage.DeleteObject ());
}


BEGIN_MESSAGE_MAP(CSettingsSheet, CPropertySheet)
	//{{AFX_MSG_MAP(CSettingsSheet)
	ON_WM_CREATE()
	//}}AFX_MSG_MAP
    ON_MESSAGE(WM_RESIZEPAGE, OnResizePage)
	ON_BN_CLICKED(ID_APPLY_NOW, OnApply)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSettingsSheet message handlers
BOOL CSettingsSheet::LoadSettings(LPCTSTR pFileName)
{
#if  defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION)
    return 
        (
		 m_pageMain.LoadConfig(pFileName) &&         // Load Config
		 m_pageMode.LoadSettings(pFileName) &&
		 m_pageNandFlash.LoadSettings( pFileName )&&
		 m_pageCalibration.LoadSettings(pFileName) &&
		 m_pageMultiLang.LoadSettings(pFileName)
		 );
#else
    return 
        (
		 m_pageMain.LoadSettings(pFileName) &&       // Load Settings
		 m_pageNandFlash.LoadSettings( pFileName )&&
         m_pageMode.LoadSettings(pFileName) &&          
		 m_pageCalibration.LoadSettings(pFileName) &&
		 m_pageMultiLang.LoadSettings(pFileName) &&
		 m_pageFlashOpt.LoadSettings(pFileName)
        );
#endif
}

BOOL CSettingsSheet::SaveSettings(LPCTSTR pFileName)
{
	DeleteFile( pFileName ); 
	
#if  defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION)
	return ( m_pageMain.SaveSettings(pFileName)&&
		     m_pageNandFlash.SaveSettings( pFileName )&&
		     m_pageMode.SaveSettings(pFileName));
#else
    return ( m_pageMain.SaveSettings(pFileName) &&
           m_pageMode.SaveSettings(pFileName) &&
           m_pageCalibration.SaveSettings( pFileName ) && 
           m_pageNandFlash.SaveSettings( pFileName )&&
		   m_pageFlashOpt.SaveSettings(pFileName));
#endif
}

int CSettingsSheet::GetBaudRate()
{
    return m_pageMain.m_nBaudRate;
}

int CSettingsSheet::GetComPort()
{
    return m_pageMain.m_nComPort;
}


int CSettingsSheet::GetDownloadFile( CStringArray& aryDownloadFile  )
{
    aryDownloadFile.Copy( m_pageMain.m_arrFileName );
	return m_pageMain.m_arrFileName.GetSize();
}

BOOL CSettingsSheet::GetCmdBootFlag()
{
    return m_pageMode.m_bCmdBoot;
}

DWORD CSettingsSheet::GetWaitTimeForNextChip()
{
    return _ttol( m_pageMode.m_strWaitTime );
}

DWORD CSettingsSheet::GetWaitTimeForBootMode()
{
    return _ttol( m_pageMode.m_strWaitTimeForBoot );
}

void CSettingsSheet::BuildPropPageArray()
{
    CPropertySheet::BuildPropPageArray();
    
    // get first page
    CPropertyPage* pPage = GetPage (0);
    ASSERT (pPage);
    
    // dialog template class in afxpriv.h
    CDialogTemplate dlgtemp;
    // load the dialog template
    VERIFY (dlgtemp.Load (pPage->m_psp.pszTemplate));
    // get the font information
    CString strFace;
    WORD	wSize;
    VERIFY (dlgtemp.GetFont (strFace, wSize));
    if (m_fntPage.m_hObject)
        VERIFY (m_fntPage.DeleteObject ());
    // create a font using the info from first page
    VERIFY (m_fntPage.CreatePointFont (wSize*10, strFace));
}


BOOL CSettingsSheet::OnInitDialog() 
{
    CPropertySheet::OnInitDialog();


	CWnd *pWnd = GetDlgItem(IDOK);
	if(pWnd != NULL)
	{
		pWnd->SetWindowText(_T("OK"));
	}

	pWnd = GetDlgItem(IDCANCEL);
	if(pWnd != NULL)
	{
		pWnd->SetWindowText(_T("Cancel"));
	}
	
	pWnd = GetDlgItem(ID_APPLY_NOW);
	if(pWnd != NULL)
	{
#if defined(_SPUPGRADE) || defined(_DOWNLOAD_FOR_PRODUCTION)
    	pWnd->SetWindowText(_T("Apply"));				
#else
		pWnd->SetWindowText(_T("Packet"));
		pWnd->EnableWindow(TRUE);
#endif
	}

	
    
    g_bInitSheet = TRUE;
    // get the font for the first active page
    CPropertyPage* pCurActPage = GetActivePage ();
    ASSERT (pCurActPage);
    
    // change the font for the sheet
    ChangeDialogFont (this, &m_fntPage, CDF_CENTER);

    // change the font for each page
    for (int iCntr = 0; iCntr < GetPageCount (); iCntr++)
    {
        VERIFY (SetActivePage (iCntr));
        CPropertyPage *pPage = GetActivePage ();
        ASSERT (pPage);
        ChangeDialogFont (pPage, &m_fntPage, CDF_CENTER);
    }
   
    VERIFY (SetActivePage (pCurActPage));
    
    Resize( 0, 0 );
    g_bInitSheet = FALSE;


 	if(g_theApp.m_bCMDPackage)
 	{
 		SetWindowPos(&wndTop,0,0,0,0,NULL);
		CenterWindow();
 	}

    return TRUE;
}


BOOL CSettingsSheet::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) 
{
    NMHDR* pnmh = (LPNMHDR) lParam;
    
    // the sheet resizes the page whenever it is activated so we need to size it correctly
    if (TCN_SELCHANGE == pnmh->code)
        PostMessage (WM_RESIZEPAGE);
    
    return CPropertySheet::OnNotify(wParam, lParam, pResult);
}

LONG CSettingsSheet::OnResizePage (UINT, LONG)
{
    // resize the page
    CPropertyPage* pPage = GetActivePage ();
    ASSERT (pPage);
    pPage->MoveWindow (&m_rctPage);
    
    return 0;
}

BOOL CSettingsSheet::OnCommand(WPARAM wParam, LPARAM lParam) 
{
    // the sheet resizes the page whenever the Apply button is clicked so we need to size it correctly
    if (ID_APPLY_NOW == wParam ||
        ID_WIZNEXT == wParam ||
        ID_WIZBACK == wParam)
        PostMessage (WM_RESIZEPAGE);
    
    return CPropertySheet::OnCommand(wParam, lParam);
}

void CSettingsSheet::Resize( int nChangeWidth, int nChangeHeight  )
{
    RECT rc;
    
    // resize the sheet
    //@ Liu Kai 2004-11-19
    // Avoid flickering
    GetWindowRect (&rc);
    rc.left -= nChangeWidth / 2;
    rc.top -= nChangeHeight / 2;
    rc.right += nChangeWidth / 2;
    rc.bottom += nChangeHeight / 2;

    MoveWindow (&rc);
    
    // resize the CTabCtrl
    CTabCtrl* pTab = GetTabControl ();
    ASSERT (pTab);
    pTab->GetWindowRect (&rc);
    ScreenToClient (&rc);
    rc.right += nChangeWidth;
    rc.bottom += nChangeHeight;
    pTab->MoveWindow (&rc);
    
    // resize the page
    CPropertyPage* pPage = GetActivePage ();
    ASSERT (pPage);
    // store page size in m_PageRect
    pPage->GetWindowRect (&m_rctPage);
    ScreenToClient (&m_rctPage);
    m_rctPage.right += nChangeWidth;
    m_rctPage.bottom += nChangeHeight;
    pPage->MoveWindow (&m_rctPage);
    
    // move the OK, Cancel, and Apply buttons
    CWnd* pWnd = GetDlgItem(IDOK);
    pWnd->GetWindowRect(&rc);
    rc.bottom += nChangeHeight;
    rc.top += nChangeHeight;
    ScreenToClient(&rc);
    pWnd->MoveWindow(&rc);
    
    pWnd = GetDlgItem(IDCANCEL);
    pWnd->GetWindowRect(&rc);
    rc.bottom += nChangeHeight;
    rc.top += nChangeHeight;
    ScreenToClient(&rc);
    pWnd->MoveWindow(&rc);
    
    pWnd = GetDlgItem(ID_APPLY_NOW);
    pWnd->GetWindowRect(&rc);
    rc.bottom += nChangeHeight;
    rc.top += nChangeHeight;
    ScreenToClient(&rc);
    pWnd->MoveWindow(&rc);
}

int CSettingsSheet::GetRepartitionFlag()
{
//#ifndef _SPUPGRADE
//    return m_pageNandFlash.m_nRepartitionFlag;
//#else
//    return m_pageMain.m_bph.dwNandStrategy;
//#endif
	return m_pageNandFlash.m_nRepartitionFlag;
}

int CSettingsSheet::GetFlashPageType()
{    
//#ifndef _SPUPGRADE
//    return m_pageNandFlash.m_nFlashType;
//#else
//    return m_pageMain.m_bph.dwNandPageType;
//#endif
	return m_pageNandFlash.m_nFlashType;
}

BOOL CSettingsSheet::IsNandFlash()
{
    return m_pageMain.m_pCurProductInfo->dwFlashType;
}

BOOL  CSettingsSheet::IsProdDualMode()
{
	return m_pageMain.m_pCurProductInfo->dwMode;
}

BOOL  CSettingsSheet::IsNvBaseChange()
{
	if(m_pageMain.m_pCurProductInfo->dwNvBaseChangeFlag == 0)
		return FALSE;
	else
		return TRUE;
}

int  CSettingsSheet::GetNvNewBasePosition()
{
	return m_pageMain.m_pCurProductInfo->dwNvNewBasePosition;
}

BOOL  CSettingsSheet::IsDualMode()
{
	if(IsProdDualMode())
	{
		//GSM and TD is not omitted
		if(m_pageMain.m_arrFileName.GetAt(3).CompareNoCase(FILE_OMIT) != 0 &&
			m_pageMain.m_arrFileName.GetAt(4).CompareNoCase(FILE_OMIT) != 0)
			return TRUE;
		else
			return FALSE;
	}
	else
		return FALSE;
}

BOOL CSettingsSheet::IsMainPageInit()
{
	return m_pageMain.m_bInit;
}

int CSettingsSheet::GetFileInfo(LPCTSTR lpszFileID, LPDWORD ppFileInfo)
{
	return m_pageMain.GetFileInfo(lpszFileID,ppFileInfo);
// 	ASSERT( lpszFileID != NULL );
// 
// 	int nCount = m_pageMain.m_pCurProductInfo->dwFileCount;
// 	PFILE_INFO_T pFileInfo= m_pageMain.m_pCurProductInfo->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;
}

CString CSettingsSheet::GetDownloadFilePath(LPCTSTR lpszFileID)
{
	int nIndex = GetFileInfo(lpszFileID,NULL);
	if(nIndex == -1)
		return _T("");
	else
		return m_pageMain.m_arrFileName.GetAt(nIndex);
}


BOOL CSettingsSheet::IsBackupNV()
{
	return m_pageCalibration.m_lstBackup.m_bBackNV || IsBackupLang();
}

int CSettingsSheet::GetNvBkpItemCount()
{
	return m_pageCalibration.m_lstBackup.m_nNvBkpItmCount;
}

PNV_BACKUP_ITEM_T CSettingsSheet::GetNvBkpItemInfo(int nIndex)
{
	int nUper = GetNvBkpItemCount();
	ASSERT(nIndex>=0 && nIndex<nUper );
	
	return m_pageCalibration.m_lstBackup.m_pNvBkpItmArray + nIndex;
}

BOOL CSettingsSheet::LoadPacket(LPCTSTR pFileName)
{
	return m_pageMain.LoadPacket(pFileName);
}

BOOL CSettingsSheet::GetFlashBaseIndex(const DWORD dwFlashType, DWORD &dwIndex)
{
	int nFlashIDCount = m_pageMain.m_pCurProductInfo->dwFlashIDCount;

	BOOL bOK = FALSE;
	for(int i = 0 ;i<nFlashIDCount; i++)
	{
		if(m_pageMain.m_pCurProductInfo->aFlashInfo[i].dwID == dwFlashType)
		{
			dwIndex = m_pageMain.m_pCurProductInfo->aFlashInfo[i].dwBaseIndex;
			bOK = TRUE;
			break;
		}
	}
	return bOK;
}

BOOL CSettingsSheet::IsUseFlashType()
{
	if(m_pageMain.m_pCurProductInfo->dwUseFlashIdInfo == 0)
		return FALSE;
	else
		return TRUE;
}

BOOL CSettingsSheet::IsUseFlashSpec()
{
	if(m_pageMain.m_pCurProductInfo->dwUseFlashIdSpec == 0)
		return FALSE;
	else
		return TRUE;
}

BOOL CSettingsSheet::IsReadFlashInFDL2()
{
	if(!IsNandFlash())
		return FALSE;

	if(!IsBackupNV())
		return FALSE;

	if(!(m_pageNandFlash.m_nRepartitionFlag == 0 || m_pageNandFlash.m_nRepartitionFlag == 3))
		return FALSE;

	int nIndex = GetFileInfo(_T("NV"),NULL);
	if(nIndex == -1)
		return FALSE;

	if(m_pageMain.m_arrFileName.GetAt(nIndex).CompareNoCase(FILE_OMIT) == 0)
		return FALSE;

	return TRUE;
}

void CSettingsSheet::OnApply()
{
	if(!g_theApp.m_bCMDPackage)
	{
		if(AfxMessageBox(_T("Do packet operation right now?"),MB_YESNO) == IDNO)
			return;
	}
	m_pageMain.DoPacket();
}

BOOL    CSettingsSheet::IsNVSaveToLocal()
{
	return m_pageCalibration.m_bSaveToLocal;
}

CString CSettingsSheet::GetNVSavePath()
{
	return m_pageCalibration.m_strLocalPath;
}

BOOL CSettingsSheet::IsBackupLang()
{
	return m_pageMultiLang.m_bBackupLang;
}
WORD CSettingsSheet::GetLangNVItemID()
{
	return m_pageMain.m_wLangNVItemID;
}

BOOL CSettingsSheet::IsHasLang()
{
	return m_pageMultiLang.m_bRightNV;
}

BOOL CSettingsSheet::IsNVOrgDownload()
{
	if(m_pageMain.m_pCurProductInfo->dwNVOrgFlag != 0 && IsOmaDM())
		return TRUE;
	else
		return FALSE;
}

int CSettingsSheet::GetNVOrgBasePosition()
{
	return m_pageMain.m_pCurProductInfo->dwNVOrgBasePosition;
}

BOOL CSettingsSheet::IsOmaDM()
{
	return m_pageMain.m_bOmaDM;
}


int CSettingsSheet::GetFlashOprFileInfo(CUIntArray &agFlashOpr)
{
	agFlashOpr.RemoveAll();
	if( m_pageFlashOpt.m_bActiveRead && m_pageFlashOpt.m_agFlashOpr.GetSize()>0)
	{
	   agFlashOpr.Copy(m_pageFlashOpt.m_agFlashOpr);
	   return agFlashOpr.GetSize();
	}
	else
	{
		return 0;
	}
	   
}

BOOL CSettingsSheet::IsEnableChipDspMap()
{
	return m_pageMain.m_bEnableChipDspMap;
}

int CSettingsSheet::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CPropertySheet::OnCreate(lpCreateStruct) == -1)
		return -1;	
	// TODO: Add your specialized creation code here

	if(g_theApp.m_bCMDPackage)
	{
		PostMessage(WM_COMMAND,ID_APPLY_NOW);
	}
	
	return 0;
}


