// MCSDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MCS.h"
#include "MCSDlg.h"

#include "HalSIS.h"
// zlib header file
#include "zlib.h"

// #include <winioctl.h>
#include <fcntl.h>
#include <io.h>
#include <imagehlp.h >
#include <shlwapi.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()

/////////////////////////////////////////////////////////////////////////////
// CMCSDlg dialog

CMCSDlg::CMCSDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMCSDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMCSDlg)
	
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	
	m_pThread = NULL;
	m_bThread = FALSE;
}

void CMCSDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMCSDlg)
	DDX_Control(pDX, IDC_PROGRESS1, m_wndProgressCtrl);
	DDX_Control(pDX, IDC_LIST1, m_List1);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMCSDlg, CDialog)
//{{AFX_MSG_MAP(CMCSDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnStop)
ON_BN_CLICKED(IDC_BUTTON2, OnTest)
ON_WM_DROPFILES()
ON_COMMAND(ID_MCS_FILE_OPEN, OnMcsFileOpen)
ON_COMMAND(ID_MCS_FILE_CLOSE, OnMcsFileClose)
ON_COMMAND(ID_MCS_HELP_ABOUT, OnMcsHelpAbout)
	ON_COMMAND(ID_MENUITEM_LISTCLEAR, OnMenuitemListclear)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMCSDlg message handlers

BOOL CMCSDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	// 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
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	int nMaxCount = 1024;
	GetWindowText(m_windowText, nMaxCount);
	
	m_wndProgressCtrl.SetRange(0, 100);
	m_wndProgressCtrl.SetStep(1);
	m_wndProgressCtrl.SetPos(0);
	
	m_List1.DeleteAllItems();
	
	DWORD dwExStyle = ListView_GetExtendedListViewStyle(m_List1.m_hWnd); 
	dwExStyle |= LVS_EX_FULLROWSELECT; 
	ListView_SetExtendedListViewStyle(m_List1.m_hWnd, dwExStyle); 
	
	LV_COLUMN lv_col;
	lv_col.mask = LVCF_TEXT | LVCF_WIDTH;
	
	lv_col.cx = NO_COLUMN;
	lv_col.pszText = "No.";
	m_List1.InsertColumn(0, &lv_col);
	
	lv_col.cx = FILE_NAME_COLUMN;
	lv_col.pszText = "Dst File Name";
	m_List1.InsertColumn(1, &lv_col);
	
	lv_col.cx = LANGUAGE_COLUMN;
	lv_col.pszText = "Src File Name";
	m_List1.InsertColumn(2, &lv_col);

	lv_col.cx = LANGUAGE_COLUMN;
	lv_col.pszText = "Pkg Type";
	m_List1.InsertColumn(3, &lv_col);

	lv_col.cx = LANGUAGE_COLUMN;
	lv_col.pszText = "Lang Cnt";
	m_List1.InsertColumn(4, &lv_col);

	lv_col.cx = TYPE_COLUMN;
	lv_col.pszText = "F. Type";
	m_List1.InsertColumn(5, &lv_col);
	
	lv_col.cx = OPTION_COLUMN;
	lv_col.pszText = "F. Option";
	m_List1.InsertColumn(6, &lv_col);
	
	lv_col.cx = COMPRESSED_SIZE_COLUMN;
	lv_col.pszText = "Comp. Size";
	m_List1.InsertColumn(7, &lv_col);
	
	lv_col.cx = ORIGINAL_SIZE_COLUMN;
	lv_col.pszText = "Org. Size";
	m_List1.InsertColumn(8, &lv_col);
	
	lv_col.cx = OFFSET_COLUMN;
	lv_col.pszText = "Offset";
	m_List1.InsertColumn(9, &lv_col);
	
	if(__argc == 2){
		strcpy(m_fileNameBuf, __argv[1]);
		kickCMSBody();
	}
	
	GetWindowRect(&m_r);
	MoveWindow(m_r.left, m_r.top, m_r.Width(), m_r.Height() * 3 / 4, TRUE);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMCSDlg::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 CMCSDlg::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
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMCSDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

// --- For Thread Control ---

void CMCSDlg::kickCMSBody()
{
	GetWindowRect(&m_r);
	MoveWindow(m_r.left, m_r.top, m_r.Width(), m_r.Height() * 4 / 3, TRUE);
		
	// Put file name on Window Title
	char newWindowText[MAX_PATH];
	
	strcpy(newWindowText, m_windowText);
	strcat(newWindowText, " - ");
	strcat(newWindowText, m_fileNameBuf);
	SetWindowText(newWindowText);
	
	// Kick Filter
	int i;
	for(i = m_List1.GetItemCount();i >= 0;i--){
		m_List1.DeleteItem(i);
	}
	
	m_bThread = TRUE;
	m_pThread = AfxBeginThread(ThreadFuncDownload, this);
}


UINT CMCSDlg::ThreadFuncDownload(LPVOID pParam)
{
	((CMCSDlg*)pParam)->MCSFilter();
	
	return 0;
}

void CMCSDlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	if(!m_pThread){
		return;
	}
	
	if(m_bThread){
		m_pThread->SuspendThread();
		int ret = MessageBox("Really Abort ?", "WinHal", MB_YESNO);
		
		if(ret == IDYES){
			m_bThread = FALSE;
			m_pThread->ResumeThread();
		}
		else{
			m_pThread->ResumeThread();
		}
	}
	else
		AfxMessageBox("Abort Soon.");
	
}

void CMCSDlg::MCSFilter()
{
	char mbsBfr[MAX_PATH];
	int i, nowPercent = 0, lastPercent = 0;
	CString s_percent;

	CHalSIS::getDirectory(mbsBfr, m_fileNameBuf);	// C:/xxx/xxx/.

	CHalSIS* pSIS = new CHalSIS(m_fileNameBuf /*SIS file path*/, 
		                        mbsBfr /*destination directory*/);

	try {
		pSIS->ReadHeaderTableFixedPart(); // to obtain SIS header info

		// m_SelectedLanguageIndex setting
		if(pSIS->m_LanguageCount > 1){
			// Enquiry only when more than one language exist
			m_DlgLanguSelect.m_LanguageCount = pSIS->m_LanguageCount;
			for(i = 0;i < pSIS->m_LanguageCount;i++){
				m_DlgLanguSelect.m_Languages[i] = pSIS->m_Languages[i];
			}
			m_DlgLanguSelect.DoModal();
			if(m_DlgLanguSelect.m_SelectedLanguageIndex >= 0){
				// update pSIS->m_SelectedLanguageIndex if the given index is valid
				pSIS->m_SelectedLanguageIndex = m_DlgLanguSelect.m_SelectedLanguageIndex;
			}
		}

		pSIS->ReadHeaderTableDependencyPart();

		// Display file header information
		displayHeaderTable(pSIS);

		pSIS->ReadPackageInfo(); // to obtain FILE info to be extracted

		// Display file information to extract
		for (i = 0; i < pSIS->m_FileCount && m_bThread; i++)
		{
			makeCMSList(i, &pSIS->m_pPackage[i]);
		}

		// Selectable drive setting 
		m_DlgDriveSelect.m_installDriveSetting = pSIS->m_installDriveSetting; // Copy default drive
		m_DlgDriveSelect.DoModal();
		pSIS->m_installDriveSetting = m_DlgDriveSelect.m_installDriveSetting; // Set selectable drive		

		// generate System/install/*.SIS file
		pSIS->CreateInstallSIS();

		// Display install drive
		mbsBfr[0] = pSIS->m_installDriveSetting;
		mbsBfr[1] = ':';
		mbsBfr[2] = '\0';
		GetDlgItem(IDC_STATIC_DRIVE)->SetWindowText(mbsBfr);

		// extract files
		for (i = 0; i < pSIS->m_FileCount && m_bThread; i++)
		{
			pSIS->ExtractPackage(&pSIS->m_pPackage[i]);

			// Progress Bar handling
			nowPercent = i * 100 / pSIS->m_FileCount + 1;
		
			if(lastPercent != nowPercent){
				m_wndProgressCtrl.SetPos(nowPercent);
				s_percent.Format("%d", nowPercent);
				GetDlgItem(IDC_STATIC_TRANSFER_VALUE)->SetWindowText(s_percent);
				lastPercent = nowPercent;
			}
		}
	} catch (char *pErrStr ) {
		MessageBox(pErrStr, "CHalSIS error!!", MB_ICONSTOP);
	}


	// --- Thread Control ---
	m_bThread = FALSE;
	m_pThread = NULL;
	
	GetWindowRect(&m_r);
	MoveWindow(m_r.left, m_r.top, m_r.Width(), m_r.Height() * 3 / 4, TRUE);

	//	OnCancel();

	delete((CHalSIS*) pSIS);
}


void CMCSDlg::OnTest() 
{
	// TODO: Add your control notification handler code here
	// 
	CFileDialog dialog(
		TRUE,
		NULL,
		NULL,
		OFN_FILEMUSTEXIST | OFN_SHOWHELP,
		"Symbian package file (*.sis)|*.sis||",
		NULL
		);
	if(dialog.DoModal() == IDOK){
		// Prepare CString -> char
		CString workCStr;
		
		workCStr = dialog.GetPathName();
		strcpy(m_fileNameBuf, workCStr.GetBuffer(512));
		
		kickCMSBody();
	}
}

BOOL CMCSDlg::PreCreateWindow(CREATESTRUCT& cs) 
{
	// TODO: Add your specialized code here and/or call the base class
	cs.style = (cs.style & ~LVS_TYPEMASK) | LVS_REPORT;
	cs.style |= LVS_AUTOARRANGE;
	
	return CDialog::PreCreateWindow(cs);
}

void CMCSDlg::makeCMSList(int fileCount, HalSISPackage *pkg)
{
	CString s_no, s_fileName, s_language, s_type, s_option, s_compressedSize, s_originalSize, s_offset, s_packageType;
	char mbsBfr[MAX_PATH];
	int n;
	
	n = 0;
	
	// Get String
	s_no.Format("%02d", fileCount + 1);
	s_packageType.Format("%X", pkg->m_packageType);
	s_language.Format("%d", pkg->m_languageCount); // Language count is temporarily set.
	s_type.Format("%X", pkg->m_FileInfo_type);
	s_option.Format("%X", pkg->m_FileInfo_option);
	s_compressedSize.Format("%04X", pkg->m_FileInfo_compressedSize[pkg->m_selectedLanguageIndex]);
	s_originalSize.Format("%04X", pkg->m_FileInfo_originalSize[pkg->m_selectedLanguageIndex]);
	s_offset.Format("%04X", pkg->m_FileInfo_offset[pkg->m_selectedLanguageIndex]); // used to be m_FileInfo_offsetEach
	
	
	n = m_List1.InsertItem(m_List1.GetItemCount(), s_no);
	wcstombs(mbsBfr, pkg->m_FileInfo_dstFileName, MAX_PATH);
	if(mbsBfr[0] == '\0')
	{
		strcpy(mbsBfr, "#### Null ####");
	}
	m_List1.SetItemText(n, 1, mbsBfr);
	wcstombs(mbsBfr, pkg->m_FileInfo_srcFileName, MAX_PATH);
	if(mbsBfr[0] == '\0')
	{
		strcpy(mbsBfr, "#### Null ####");
	}
	m_List1.SetItemText(n, 2, mbsBfr);
	m_List1.SetItemText(n, 3, s_packageType);
	m_List1.SetItemText(n, 4, s_language);
	m_List1.SetItemText(n, 5, s_type);
	m_List1.SetItemText(n, 6, s_option);
	m_List1.SetItemText(n, 7, s_compressedSize);
	m_List1.SetItemText(n, 8, s_originalSize);
	m_List1.SetItemText(n, 9, s_offset);
}


void CMCSDlg::OnDropFiles(HDROP hDropInfo) 
{
	// TODO: Add your message handler code here and/or call default
	int ncnt = 0;
    UINT unSize ;
    char szPath[_MAX_PATH+1];
	
	if(!m_bThread){
		while(1){
			// ドロップされた内容を取得
			unSize = 
				::DragQueryFile( hDropInfo, 
				ncnt++,
				szPath, 
				_MAX_PATH);
			
			if( unSize <= 0){
				break;
			}
			else{
				strcpy(m_fileNameBuf, szPath);
				kickCMSBody();
			}
		}
	}
	CDialog::OnDropFiles(hDropInfo);
}

void CMCSDlg::OnMcsFileOpen() 
{
	// TODO: Add your command handler code here
	OnTest();
}

void CMCSDlg::OnMcsFileClose() 
{
	// TODO: Add your command handler code here
	OnCancel();
}

void CMCSDlg::OnMcsHelpAbout() 
{
	// TODO: Add your command handler code here
	CAboutDlg dlgAbout;
	dlgAbout.DoModal();
}


// Count 0x5C in strings
int CMCSDlg::getNumOfDirFromDisFileName(char *aDistFileName)
{
	int i, numOfDir;
	i = 0;
	numOfDir = 0;
	while(aDistFileName[i] != 0x00){
		if(aDistFileName[i] == 0x5C){
			numOfDir++;
		}
		i++;
	}
	return numOfDir;
}

void CMCSDlg::displayHeaderTable(CHalSIS *pParams)
{
	CString strHeaderData, strHeaderData0, strHeaderData1, strHeaderData2;
	char mbsBfr[MAX_PATH];

	strHeaderData0.Format("%08X", pParams->m_UID0);
	GetDlgItem(IDC_UID)->SetWindowText(strHeaderData0);

	wcstombs(mbsBfr, pParams->m_AppName, MAX_PATH);
	GetDlgItem(IDC_STATIC_APPNAME)->SetWindowText(mbsBfr);

	strHeaderData0.Format("%d.", pParams->m_Version0);
	strHeaderData1.Format(" %d", pParams->m_Version1);
	strHeaderData2.Format(" build %d", pParams->m_Version2);
	strHeaderData = strHeaderData0 + strHeaderData1 + strHeaderData2;
	GetDlgItem(IDC_STATIC_VERSION0)->SetWindowText(strHeaderData);

	strHeaderData.Format("%04X", pParams->m_SpaceUsed);
	GetDlgItem(IDC_STATIC_SPACE_USED)->SetWindowText(strHeaderData);

	strHeaderData.Format("%04X", pParams->m_MaxInstallSize);
	GetDlgItem(IDC_STATIC_MAX_SIZE)->SetWindowText(strHeaderData);

	GetDlgItem(IDC_STATIC_LANGUAGE)->SetWindowText(tbl_languages[pParams->m_Languages[pParams->m_SelectedLanguageIndex] - 1]);
}

void CMCSDlg::OnMenuitemListclear() 
{
	// TODO: この位置にコマンド ハンドラ用のコードを追加してください
	m_List1.DeleteAllItems();
}
