#include "stdafx.h"
#include "sxbmem.h"
#include "RegNames.h"

#include "DigiKme.h"

#include "Dlg.h"

extern CSxbmemApp theApp;

IMPLEMENT_DYNCREATE(CAdapter, CObject);

CTypedPtrMap<CMapStringToPtr,CString,CRuntimeClass *> CAdapter::m_Registry;

void CAdapter::GetDriverInfo(sDriverInfo& Info, const CString& keyName)
{
	HKEY digisoft;
	CString path = c_pszNTDigiSoftwareBase;
	
	path += '\\' + keyName + "\\CurrentVersion";

 	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, &digisoft) == ERROR_SUCCESS) {
		BYTE s[256];
		DWORD Type = REG_SZ, Size = 256;
		RegQueryValueEx(digisoft, "Title", 0, &Type, s, &Size);

		for (BYTE *t = s; *t == ' '; t++);
		Info.m_DriverName = (LPCSTR)t;

		Size = 256;
		RegQueryValueEx(digisoft, "ServiceName", 0, &Type, s, &Size);
		HKEY digiservice;
		path = CString(c_pszNTServiceBase) + '\\' + s;
		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, &digiservice) == ERROR_SUCCESS) {
			TCHAR expand[256];
			TCHAR fpath[256];
			
			Type = REG_EXPAND_SZ;
			Size = 256;
			RegQueryValueEx(digiservice, "ImagePath", 0, &Type, (LPBYTE)expand, &Size);
			if (strstr(expand, "\\SystemRoot") == expand)
				strcpy(expand, CString("%SystemRoot%") + &expand[11]);
			ExpandEnvironmentStrings((LPCTSTR)expand, fpath, 256);
						
			CFileStatus status;
			if (CFile::GetStatus(fpath, status)) {
				DWORD zero = 0, size = GetFileVersionInfoSize(fpath, &zero);
				if (size > 0 && zero == 0) {
					BYTE *buf = new BYTE[size];

					if (GetFileVersionInfo(fpath, NULL, size, buf)) {
						LPVOID lpBuffer;
						UINT dwBytes;
						
						if (VerQueryValue(buf, TEXT("\\StringFileInfo\\040904B0\\FileVersion"), &lpBuffer, &dwBytes))
							Info.m_DriverVersion = (LPCSTR)lpBuffer;
						}  
					delete[] buf;
					}
				Info.m_DriverDate = status.m_mtime.Format("%c");
				}

			RegCloseKey(digiservice);
			}
		RegCloseKey(digisoft);
		}
}


BOOL CAdapter::TestAdapter(const CString& DeviceName, CString& error)
{
	if ((m_hFile = CreateFile(DeviceName,
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
		NULL)) == INVALID_HANDLE_VALUE)
	{
		m_hFile = NULL;
		error.Format("Couldn't open %s\n", DeviceName);
		return FALSE;
	}

  UCHAR Buffer[256];
	DWORD size = 256;
	
	BOOL result = GetMemory(0x10000, Buffer, &size);
	if (!result)
		error = "Failed to get data from the adapter";

	return result;
}

void CAdapter::DoSummaryDlg(const CString& dsName)
{
	CSummaryDlg dlg;

	dlg.m_FirmwareVersion = m_FirmwareVersion;
	dlg.m_Comment = theApp.GetProfileString("Settings", dsName, "");
	dlg.m_pDrivers = &m_Drivers;

	if (dlg.DoModal() == IDOK)
		theApp.WriteProfileString("Settings", dsName, dlg.m_Comment);
}

