//---------------------------------
// Name:			UpgradingDialog.cpp
// Purpose:			Dialog showing upgrade progress
// Toolchain(s):	Microsoft Visual C++
// Creation date:	26-May-06
// Created by:		JJo
//---------------------------------

//---------------------------------
// Includes

#include "UpgradingDialog.h"

//---------------------------------
// Message map

BEGIN_MESSAGE_MAP(UpgradingDialog, CDialog)
	ON_MESSAGE(MSG_PROGRESS, OnProgress)
	ON_MESSAGE(MSG_FINISHED, OnFinished)
	ON_BN_CLICKED(IDC_CANCEL, OnCancelClicked)
	ON_MESSAGE(MSG_SHOULDCLOSE, OnShouldClose)
END_MESSAGE_MAP()

//---------------------------------
// Class

/**
 * Name:		UpgradingDialog
 * Purpose:		Constructor for the UpgradingDialog class
 */
UpgradingDialog::UpgradingDialog(CWnd * pParent, Configuration * pConfiguration) :
CDialog(IDD_UPGRADINGDIALOG, pParent),
m_pConfiguration(pConfiguration),
m_close(FALSE) {}

/**
 * Name:		~UpgradingDialog
 * Purpose:		Destructor for the UpgradingDialog class
 */
UpgradingDialog::~UpgradingDialog() {}

/**
 * Name:		OnInitDialog
 * Purpose:		Handles initialization of dialog
 */
BOOL UpgradingDialog::OnInitDialog() {

	CDialog::OnInitDialog();

	// Get control handles
	this->m_pProgress = (CProgressCtrl *) this->GetDlgItem(IDC_PROGRESS);
	this->m_pProgress->SetPos(0);
	this->m_pProgress->SetStep(5);
	
	// Start upgrade process
	this->m_pThread = AfxBeginThread(UpgradingDialog::Upgrade, (LPVOID) this);

	return TRUE;
}

/**
 * Name:		OnProgress
 * Purpose:		Handles progress event
 */
void UpgradingDialog::OnProgress() {

	this->m_pProgress->StepIt();
}

/**
 * Name:		OnFinished
 * Purpose:		Handles transfer finished event
 */
void UpgradingDialog::OnFinished() {

	// Beep and close window
	MessageBeep(MB_OK);
	this->EndDialog(0);
}

/**
 * Name:		OnCancelClicked
 * Purpose		Handles clicks on the cancel button
 */
void UpgradingDialog::OnCancelClicked() {

	this->m_close = TRUE;
}

/**
 * Name:		OnShouldClose
 * Purpose:		Handles the SHOULDCLOSE message
 */
LRESULT UpgradingDialog::OnShouldClose() {

	return this->m_close;
}

/**
 * Name:		Upgrade
 * Purpose:		Sends the new firmware to the target device
 * Input:
 *	- Pointer to an UpgradeWindow instance
 */
UINT UpgradingDialog::Upgrade(LPVOID pParam) {

	// Local variables
	UpgradingDialog * pUpgradingDialog = (UpgradingDialog *) pParam;
	Configuration * pConfiguration = pUpgradingDialog->m_pConfiguration;
	char * pData;
	unsigned long size;
	CFile * pFile;

	try {

		// Retrieve file info & data
		pFile = pConfiguration->GetFile();
		size = pFile->GetLength();
		pData = new char[size];
		pFile->Read(pData, size);

		// Send firmware
		pConfiguration->GetCommunication()->Send(pData, size, pUpgradingDialog->m_hWnd, size/20);

		// Cleanup
		delete pData;
	}
	catch (CException * e) {

		e->ReportError();
		e->Delete();
		pUpgradingDialog->PostMessage(MSG_FINISHED);
	}

	return 0;
}