// UpDownLoad.cpp : 实现文件
//

#include "stdafx.h"
#include "NetSDKDemo.h"
#include "NetSDKDemoDlg.h"
#include "WndCtrl.h"
#include "UpDownLoad.h"

// CUpDownLoad 对话框
IMPLEMENT_DYNAMIC(CUpDownLoad, CDialog)

CUpDownLoad::CUpDownLoad(CRect rcWnd, CWnd* pParent /*=NULL*/)
	: CDialog(CUpDownLoad::IDD, pParent)
	,m_rcClient(0, 0, rcWnd.Width(), rcWnd.Height())
{
	m_bUpgrade = FALSE;
	m_iUserID = 0;
	m_bShow = FALSE;
	m_bUpgrade = FALSE;
	memset(szVersionBuf, 0, sizeof(szVersionBuf));
	memset(szBeforeVer, 0, sizeof(szBeforeVer));
	memset(szAfterVer, 0, sizeof(szAfterVer));
	m_pDevInfo = NULL;
	m_timeElapse = 0;
	m_loginOK = FALSE;
}

CUpDownLoad::~CUpDownLoad()
{
	KillTimer(WM_TIMER_UPGRADE);
	DestroyWindow();
}

void CUpDownLoad::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_GROUP, m_ctlGroup);
	DDX_Control(pDX, IDC_ED_PATH, m_ctlEDPath);
	DDX_Control(pDX, IDC_STATIC_DEVIP, m_ctlDevIP);
	DDX_Control(pDX, IDC_ED_FIRMWARE_PATH, m_ctlFirmWarePath);
	DDX_Control(pDX, IDC_PROGRESS_UPGRADE, m_ctlUpgradeProcess);
}


BEGIN_MESSAGE_MAP(CUpDownLoad, CDialog)
	ON_BN_CLICKED(IDC_BTN_UPLOAD, &CUpDownLoad::OnBnClickedBtnUpload)
	ON_BN_CLICKED(IDC_BTN_DOWNLOAD, &CUpDownLoad::OnBnClickedBtnDownload)
	ON_BN_CLICKED(IDC_BTN_LAODING, &CUpDownLoad::OnBnClickedBtnLaoding)
	ON_BN_CLICKED(IDC_BTN_UPGRADE, &CUpDownLoad::OnBnClickedBtnUpgrade)
	ON_BN_CLICKED(IDC_BTN_STOP, &CUpDownLoad::OnBnClickedBtnStop)
	ON_BN_CLICKED(IDC_BTN_LOADING, &CUpDownLoad::OnBnClickedBtnLoading)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BTN_REBOOT, &CUpDownLoad::OnBnClickedBtnReboot)
	ON_BN_CLICKED(IDC_BTN_FACTORYSET, &CUpDownLoad::OnBnClickedBtnFactoryset)
	ON_MESSAGE(USER_STATUS_EVENT, &CUpDownLoad::OnStatusEvent)
	ON_WM_SHOWWINDOW()
END_MESSAGE_MAP()


// CUpDownLoad 消息处理程序

BOOL CUpDownLoad::OnInitDialog()
{
	CDialog::OnInitDialog();

	// TODO:  在此添加额外的初始化
	m_ctlGroup.MoveWindow(CRect(m_rcClient.left+2, m_rcClient.top,m_rcClient.Width()-2, m_rcClient.Height()-2));
	m_ctlDevIP.SetWindowText(_T(""));
	m_ctlUpgradeProcess.SetPos(0);
	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}

void CUpDownLoad::OnBnClickedBtnUpload()
{
	// TODO: 在此添加控件通知处理程序代码
	
	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}
	
	if (IDYES != MessageBox(_T("确定上传?"), _T("提示"), MB_YESNO))
	{
		return;
	}
	
// 	if (m_bUpgrade)
// 	{
// 		AfxMessageBox("正在升级请耐心稍等!!!");
// 		return ;
// 	}

	CNetSDKDemoDlg *pNetDlg = (CNetSDKDemoDlg *)GetParent();

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);

	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("该设备未连接");
		return ;
	}

	CString strPath;
	m_ctlEDPath.GetWindowText(strPath);

	if (strPath.IsEmpty())
	{
		AfxMessageBox("请加载要上传的文件");
		return ;
	}
	
	if (strcmp(".ini", strPath.Right(4)) != 0
		&& strcmp(".INI", strPath.Right(4)) != 0)
	{
		if (MessageBox("非配置文件，是否继续!!!", _T("提示"), MB_OKCANCEL) == IDCANCEL)
		{
			return;
		}
	}

	DWORD dwFileAttr = GetFileAttributes(strPath);
 	if (dwFileAttr == INVALID_FILE_ATTRIBUTES)
	{
		AfxMessageBox("连接不到指定文件，请确认路径完整性!!!");
		return;
	}


	if (iUserID != 0)
	{
		long lRet =IP_NET_DVR_SetConfigFile(iUserID, strPath.GetBuffer());
		if ( lRet != 0)
		{
			AfxMessageBox("上传失败!!可能原因：\n\t1.句柄错误\n\t2.设备未连接\n\t3.设备未登录成功\n\t4.内存不足!!");
			return ;
		}
		theApp.m_OnlyOneAction.miWhat = 1;
		theApp.m_OnlyOneAction.miUserID = iUserID;
		theApp.m_OnlyOneAction.mstrWho = strIP;
		theApp.m_OnlyOneAction.mstrMSG.Format("%s 正在上传配置文件,请等待!!!", strIP);
	}
}

void CUpDownLoad::OnBnClickedBtnDownload()
{
	// TODO: 在此添加控件通知处理程序代码
	
	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}
// 	if (m_bUpgrade)
// 	{
// 		// 正在升级
// 		AfxMessageBox("正在升级请耐心稍等!!!");
// 		return ;
// 	}

	CNetSDKDemoDlg *pNetDlg = (CNetSDKDemoDlg *)GetParent();

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);

	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("请先登录设备");
		return ;
	}

	CString strPath;
	m_ctlEDPath.GetWindowText(strPath);
	if (strPath.IsEmpty())
	{
		if(MessageBox("没有输入文件名，默认存储于[C:/TPSConfigFile.ini]","提示", MB_OKCANCEL)==IDOK)
		{
			strPath.Format("C:/TPSConfigFile.ini");
			m_ctlEDPath.SetWindowText(strPath);
		}
		else return ;
	}
	
	TCHAR szDrive[_MAX_DRIVE] = {0};
	TCHAR szDir[_MAX_DIR] = {0};
	TCHAR szName[_MAX_DIR] = {0};

	_tsplitpath(strPath, szDrive, szDir, szName, NULL);
	CString strOnlyPath;
	strOnlyPath.Format("%s%s", szDrive, szDir);

	if (strlen(szName) <= 0)
	{
		AfxMessageBox("请指定存储文件名");
		return ;
	}

	DWORD dwFileAttr = GetFileAttributes(strOnlyPath);
	if (dwFileAttr == INVALID_FILE_ATTRIBUTES)
	{
		AfxMessageBox("连接不到指定文件，请确认路径完整性!!!");
		return;
	}


	if (iUserID != 0)
	{
		//long lRet = 0;
		long lRet =IP_NET_DVR_GetConfigFile(iUserID, strPath.GetBuffer());
		if ( lRet != 0)
		{
			AfxMessageBox("下载失败!!可能原因：\n\t1.句柄错误\n\t2.设备未连接\n\t3.设备未登录成功\n\t4.内存不足!!");
		}

		theApp.m_OnlyOneAction.miWhat = 0;
		theApp.m_OnlyOneAction.miUserID = 0;
		theApp.m_OnlyOneAction.mstrWho = "";
		theApp.m_OnlyOneAction.mstrMSG = "";
	}
}

void CUpDownLoad::OnBnClickedBtnLaoding()
{
	// TODO: 在此添加控件通知处理程序代码
// 	if (m_bUpgrade)
// 	{
// 		// 正在升级
// 		return ;
// 	}

	char szFilters[]=
		"INI Files (*.ini)|*.ini|All Files (*.*)|*.*||";

	// Create an Open dialog; the default file name extension is ".my".
	CFileDialog fileDlg (TRUE, "ini", "*.ini",
		OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, szFilters, this);

	// Display the file dialog. When user clicks OK, fileDlg.DoModal() 
	// returns IDOK.
	if( fileDlg.DoModal ()==IDOK )
	{
		CString pathName = fileDlg.GetPathName();

		// Implement opening and reading file in here.
	//	...
			//Change the window's title to the opened file's title.
			//CString fileName = fileDlg.GetFileName();
	
		m_ctlEDPath.SetWindowText(pathName);
	}

}

extern HANDLE g_EVENT_GET_VERSION;

void CUpDownLoad::OnBnClickedBtnUpgrade()
{
	// TODO: 在此添加控件通知处理程序代码
	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}


	if (IDYES != MessageBox(_T("确定升级?"), _T("提示"), MB_YESNO))
	{
		return;
	}
// 	if (m_bUpgrade)
// 	{
// 		AfxMessageBox("升级中，请等待!!!");
// 		return ;
// 	}

	CNetSDKDemoDlg *pNetDlg = (CNetSDKDemoDlg *)GetParent();

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);

	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
			m_pDevInfo = pDevInfo;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("请选择登录的设备");
		return ;
	}

	CString strFirmwarePath;
	m_ctlFirmWarePath.GetWindowText(strFirmwarePath);


	if (strFirmwarePath.IsEmpty())
	{
		AfxMessageBox("请加载要升级的文件");
		return ;
	}


	DWORD dwFileAttr = GetFileAttributes(strFirmwarePath);
	if (dwFileAttr == INVALID_FILE_ATTRIBUTES)
	{
		AfxMessageBox("连接不到指定文件，请确认路径完整性!!!");
		return;
	}

	if (strcmp(strFirmwarePath.Right(4), ".bin") != 0
		&& strcmp(strFirmwarePath.Right(4), ".BIN") != 0)
	{
		if (MessageBox(_T("非升级文件，是否继续升级??"),_T("提示"), MB_OKCANCEL) == IDCANCEL)
			return  ;
	}

	
	m_bUpGetVersion = TRUE;
	memset(szBeforeVer, 0, sizeof(szBeforeVer));
	if (0 != IP_NET_DVR_SystemControl(iUserID, CMD_GET_SYSTEM_VERSION_INFO, 0, "RESPONSE_PARAM"))
	{
		m_bUpGetVersion = FALSE;
		MessageBox("获取文件版本请求失败");
		return;
	}

	if (WaitForSingleObject(g_EVENT_GET_VERSION,3000) ==WAIT_TIMEOUT)
	{
		m_bUpGetVersion = FALSE;
		MessageBox("获取文件版本失败");
		return;
	}

	m_bUpGetVersion = FALSE;
	
	GetFileVersion(szVersionBuf, szBeforeVer);

	
	int iRet = IP_NET_DVR_Upgrade(iUserID, strFirmwarePath.GetBuffer());

	if (iRet == 0)
	{
		AfxMessageBox("升级请求成功启动！");
	}
	else
	{
		AfxMessageBox("升级请求启动失败");
		return;
	}

	theApp.m_OnlyOneAction.miWhat = 3; // 固件升级
	theApp.m_OnlyOneAction.miUserID = iUserID;
	theApp.m_OnlyOneAction.mstrWho = strIP; // 谁干得，
	theApp.m_OnlyOneAction.mstrMSG.Format("%s 正在升级,请等待!!!", strIP);
	m_iUserID = iUserID;
	//m_bUpgrade = TRUE;
	SetTimer(WM_TIMER_UPGRADE, 500, NULL);
}

long CUpDownLoad::GetFileVersion(char* szVerBuf, char* outVerBuf)
{
	if (NULL == szVerBuf || NULL == outVerBuf)
	{
		return -1;
	}

	char *pTmp = strstr(szVerBuf, "FileSystemVersion");
	if (NULL == pTmp)
	{
		return -2;
	}

	strcpy(outVerBuf, pTmp);

	return 0;

}

void CUpDownLoad::OnBnClickedBtnStop()
{
	// TODO: 在此添加控件通知处理程序代码
// 	if (!m_bUpgrade)
// 	{
// 		return ;
// 	}
	if (theApp.m_OnlyOneAction.miWhat != 3)  return ;
	CNetSDKDemoDlg *pNetDlg = (CNetSDKDemoDlg *)GetParent();

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);

	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("没有找到设备");
		return ;
	}

	CString strFirmwarePath;
	m_ctlFirmWarePath.GetWindowText(strFirmwarePath);
	
	int iRet = IP_NET_DVR_CloseUpgradeHandle(iUserID);
	theApp.m_OnlyOneAction.miWhat = 0; // 空闲
	theApp.m_OnlyOneAction.miUserID = 0;
	theApp.m_OnlyOneAction.mstrWho = ""; // 谁干得，
	theApp.m_OnlyOneAction.mstrMSG = "";

	//m_bUpgrade = FALSE;
	KillTimer(WM_TIMER_UPGRADE);
	m_ctlUpgradeProcess.SetPos(0);
	
}

void CUpDownLoad::OnBnClickedBtnLoading()
{
	// TODO: 在此添加控件通知处理程序代码
	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}
// 	if (m_bUpgrade)
// 	{
// 		// 正在升级
// 		AfxMessageBox("正在升级中请等待升级完成");
// 		return ;
// 	}

	char szFilters[]=
		"BIN Files (*.bin)|*.bin|All Files (*.*)|*.*||";

	CFileDialog fileDlg (TRUE, "*", "*.bin",
		OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, szFilters, this);

	if( fileDlg.DoModal ()==IDOK )
	{
		CString pathName = fileDlg.GetPathName();
 
		m_ctlFirmWarePath.SetWindowText(pathName);
	}
}


void CUpDownLoad::SetSelIP(CString &strIP)
{
	if (theApp.m_OnlyOneAction.miWhat != 0)
		return ;
	
	m_ctlDevIP.SetWindowText(strIP);

	
}
void CUpDownLoad::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	if (nIDEvent == WM_TIMER_UPGRADE)
	{
		if (m_iUserID != 0)
		{	
			int iPos = IP_NET_DVR_GetUpgradeProgress(m_iUserID);
			if (iPos >= 100) 
			{
				TRACE("iPos = %d\n", iPos);
				int iPos = m_ctlUpgradeProcess.GetPos();
				if (iPos>0)
				{
					m_ctlUpgradeProcess.SetPos(100);
					KillTimer(WM_TIMER_UPGRADE);
					PostMessage(WM_UPLOADSUCCESS, 0, 0);
				}	
			}
			else	{
				m_ctlUpgradeProcess.SetPos(iPos);
				TRACE("iPos = %d\n", iPos);
			}
		}
	}
	else if (WM_TIMER_GETVERSION == nIDEvent)
	{
		
		if (GetTickCount() - m_timeElapse > 5*60*1000)
		{
			KillTimer(WM_TIMER_GETVERSION);
			MessageBox("升级超时！");
			return;
		}

		if (!m_loginOK)
		{
			m_pDevInfo->iUserID = 0;
			if (0 == ((CNetSDKDemoDlg *)theApp.m_pMainWnd)->m_pWndDevList->LoginDevi(m_pDevInfo) && m_pDevInfo->iUserID >0)
			{
				m_loginOK = TRUE;
			}
			else
			{
				return;
			}
		}
		
		
		m_bUpGetVersion = TRUE;
		IP_NET_DVR_SystemControl(m_pDevInfo->iUserID, CMD_GET_SYSTEM_VERSION_INFO, 0, "RESPONSE_PARAM");

		if (WaitForSingleObject(g_EVENT_GET_VERSION,2000) ==WAIT_TIMEOUT)
		{
			m_bUpGetVersion = FALSE;
			return;
		}
		

		KillTimer(WM_TIMER_GETVERSION);
		m_bUpGetVersion = FALSE;
		GetFileVersion(szVersionBuf, szAfterVer);
		if (0 != strcmp(szBeforeVer, szAfterVer))
		{
			MessageBox("升级成功！");
		}
		else
		{
			MessageBox("升级失败！");
		}
		
	}
	//m_ctlUpgradeProcess.SetPos(0);
	CDialog::OnTimer(nIDEvent);
}

BOOL CUpDownLoad::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (pMsg->message == WM_KEYDOWN)
	{
		if(pMsg->wParam == 13)
			return TRUE;
		if (pMsg->wParam == 27)
		{
			::PostMessage(GetParent()->m_hWnd, WM_KEYDOWN, 27, 0);
			return TRUE;
		}
	}
	if (pMsg->message ==WM_UPLOADSUCCESS)
	{
		m_ctlUpgradeProcess.SetPos(0);
		return TRUE;
	}
	return CDialog::PreTranslateMessage(pMsg);
}

void CUpDownLoad::OnBnClickedBtnReboot()
{
	// TODO: 在此添加控件通知处理程序代码

	((CNetSDKDemoDlg *)GetParent())->m_pMenuDlg->CloseVideo();

	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}


	if (IDYES != MessageBox(_T("确定重启?"), _T("提示"), MB_YESNO))
	{
		return;
	}

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);

	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("设备未连接!!!\n");
		return ;
	}

	long lRet = IP_NET_DVR_RebootDVR(iUserID);
	if (lRet == 0)
	{
		AfxMessageBox("设备重启成功!!!\n");
	}
	else
	{
		AfxMessageBox("设备重启失败!!!\n");
	}
	
}

void CUpDownLoad::OnBnClickedBtnFactoryset()
{
	// TODO: 在此添加控件通知处理程序代码
	((CNetSDKDemoDlg *)GetParent())->m_pMenuDlg->CloseVideo();

	if (theApp.m_OnlyOneAction.miWhat != 0)
	{
		AfxMessageBox(theApp.m_OnlyOneAction.mstrMSG);
		return ;
	}

	if (IDYES != MessageBox(_T("确定恢复出厂设置?"), _T("提示"), MB_YESNO))
	{
		return;
	}

	CString strIP;
	m_ctlDevIP.GetWindowText(strIP);
	int iUserID = 0;
	{
		CMapAutoLock Lock;	
		CDevInfo *pDevInfo = NULL;
		BOOL bFound = theApp.m_DevList.Lookup(strIP, pDevInfo);
		if (bFound)
		{
			iUserID = pDevInfo->iUserID;
		}
	}

	if (iUserID == 0)
	{
		// 设备未登录
		AfxMessageBox("设备未连接");
		return ;
	}
	long lRet = IP_NET_DVR_RestoreConfig(iUserID);
	if (lRet == 0)
	{
		IP_NET_DVR_RebootDVR(iUserID);
		AfxMessageBox("恢复出厂默认设置成功!!!");
	}
	else
	{
		AfxMessageBox("恢复出厂默认设置失败!!!");
	}
	
}

LONG __stdcall	CUpDownLoad::StatusCallBack(LONG lUser,LONG mlStateCode,char *mpResponse,void *pUser)
{	
	switch (mlStateCode)
	{
	case EVENT_DOWNLOADFAILED:
	case EVENT_DOWNLOADOK:
	case EVENT_UPLOADOK:
	case EVENT_UPLOADFAILED:
		{
			PostMessage(USER_STATUS_EVENT, mlStateCode, 0);
			if (theApp.m_OnlyOneAction.miUserID == lUser)
			{
				theApp.m_OnlyOneAction.miUserID = 0;
				theApp.m_OnlyOneAction.miWhat = 0;
				theApp.m_OnlyOneAction.mstrMSG = "";
				theApp.m_OnlyOneAction.mstrWho = "";
			}
		}
		break;
	default:break;
	}

	return 0;
}

HRESULT CUpDownLoad::OnStatusEvent(WPARAM wParam, LPARAM lParam)
{
	if (!m_bShow) return 0;
	switch (wParam)
	{
	case EVENT_DOWNLOADFAILED:
		{
			AfxMessageBox("下载失败！");
		}
		break;
	case EVENT_DOWNLOADOK:
		{
			AfxMessageBox("下载完成！");
		}
		break;
	case EVENT_UPLOADOK:
		{
			AfxMessageBox("上传完成！");
			m_timeElapse = GetTickCount();
			m_loginOK = FALSE;
			SetTimer(WM_TIMER_GETVERSION, 3000, NULL);
		}
		break;
	case EVENT_UPLOADFAILED:
		{
			AfxMessageBox("上传失败！");
		}
		break;
	}
	return 0;
}
void CUpDownLoad::OnShowWindow(BOOL bShow, UINT nStatus)
{
	CDialog::OnShowWindow(bShow, nStatus);
	m_bShow = bShow;
	// TODO: 在此处添加消息处理程序代码
}
