// Open SanAndreas
// (c) 2006-2008 Stanislav "listener" Golovin
// 
// miscellaneous file operations 
#include "stdafx.h"
#include <direct.h>
#include "ogFiles.h"

char * gtaCurrentPath = (char *)0xB71A60;
char * gtaProgramPath = (char *)0xB71AE0;

char * saveFilePrefix = (char *)0xC16F18;	// TODO: CFileMgr::saveFilePrefix

static char tmpPath[2*MAX_PATH];
CFileMgr	fileManager;	// TODO: возможно, стоит ее куда-то перенести

// TODO: убрать эту функцию как только это будет возможно
void chdirUserDir () {	
	_chdir (fileManager.userPath);
}

void chdirProgramDir (char * relPath) {	
	sprintf_s (tmpPath, 2*MAX_PATH, "%s%s", fileManager.programPath, relPath);
}


CFileMgr::CFileMgr () {
	programPath[0] = '\0';
	userPath[0]  = '\0';
}

CFileMgr::~CFileMgr() {
}

void CFileMgr::initialize() {
	// get program path
	_getcwd (programPath, MAX_PATH);
	size_t len = strlen (programPath);
	programPath[len] = '\\';
	programPath[len+1] = '\0';

	// get user path	
	HKEY hKey;
	if (!RegOpenKeyEx (HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_READ, &hKey)) {
		DWORD type;
		DWORD size;
		if (!RegQueryValueEx (hKey, "Personal", 0, &type, (LPBYTE)userPath, &size)) {
			RegCloseKey (hKey);

			len = strlen (userPath);
			strcpy_s (userPath+len, MAX_PATH-len, "\\GTA San Andreas User Files\\");
			len = strlen (userPath);
			
			HANDLE hFile = CreateFile (userPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0x2000080, NULL);
			if (hFile == INVALID_HANDLE_VALUE) 
				CreateDirectory (userPath, NULL);
			else
				CloseHandle (hFile);

			strcpy_s (tmpPath, 2*MAX_PATH, userPath);
			strcpy_s (tmpPath+len, 2*MAX_PATH-len, "Gallery");
			hFile = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0x2000080, NULL);
			if (hFile == INVALID_HANDLE_VALUE) 
				CreateDirectory (tmpPath, NULL);
			else
				CloseHandle (hFile);

			strcpy_s (tmpPath, 2*MAX_PATH, userPath);
			strcpy_s (tmpPath+len, 2*MAX_PATH-len, "User Tracks");
			hFile = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0x2000080, NULL);
			if (hFile == INVALID_HANDLE_VALUE) 
				CreateDirectory (tmpPath, NULL);
			else
				CloseHandle (hFile);			
		}
		RegCloseKey (hKey);
	} else
		strcpy_s (userPath, MAX_PATH, "data\\");
	
	// initialize save file names	(inlined >> 619040)
	sprintf_s (saveFilePrefix, 260, "%s%s", userPath, "GTASAsf");	// TODO: buffer size

	// TODO: временная заглушка для того, чтобы работало все остальное (используется для sub_538730)
	strcpy_s (gtaProgramPath, 128, programPath);

	debug ("CFileMgr::initialize: programPath = '%s', userPath = '%s'\n", programPath, userPath);
}