#include "FileCore.h"
#pragma region 文件

bool FileCore::IsExistTheFileW(wstring filePath)
{
	bool isExist = PathFileExistsW(filePath.c_str());
	return isExist;
}

bool FileCore::IsExistProductAppPath()
{
	wstring installPath = PathCore::smPath_Install + L"\\" + Product::smName_Application;
	bool isExist = PathFileExistsW(installPath.c_str());
	if (!isExist) {
		wstring installPathnoexe = PathCore::smPath_Install + L"\\" + L"PDFReaderProWin";
		isExist = PathFileExistsW(installPathnoexe.c_str());
	}
	return isExist;
}

bool FileCore::SourceFileMoveToDestionPath(wstring sourceFile, wstring destPath)
{
	wstring dest = destPath + L"\\" + Product::smName_InstallPackage;
	bool issuccess = MoveFileExW(sourceFile.c_str(), dest.c_str(), MOVEFILE_REPLACE_EXISTING);
	return issuccess;
}
#pragma endregion


#pragma region 文件夹

wstring FolderCore::GetNewSaveFolder(wstring saveFilePath, wstring oldchar, wstring newchar)
{
	while (true)
	{
		size_t pos = saveFilePath.find(oldchar);
		if (pos != wstring::npos)
		{
			WCHAR pBuf[1] = { L'\0' };
			saveFilePath.replace(pos, oldchar.length(), pBuf, 0);
			saveFilePath.insert(pos, newchar);
		}
		else
		{

			break;
		}

	}
	return saveFilePath;
}

wstring FolderCore::GetOrCreateFolderPath(wstring saveFilePath)
{
	wstring newSaveFolder = FolderCore::GetNewSaveFolder(saveFilePath, L"\\", L"/");
	BOOL isCreate = FALSE;
	if (!PathIsDirectoryW(newSaveFolder.c_str()))
		isCreate = CreateDirectory((newSaveFolder.c_str()), NULL);
	return newSaveFolder;
}

bool FolderCore::IsExistTheFolderW(wstring folderPath)
{
	BOOL isExist = PathFileExistsW(folderPath.c_str());
	return isExist;
}

bool FolderCore::IsRootDirectoryW(wstring folderPath)
{
	int first2 = folderPath.find(L"\\");
	if (first2 + 1 == folderPath.length())
	{
		return true;
	}
	else
	{
		return false;
	}
}
wstring FolderCore::AddSubFolderFromRootDirW(wstring folderPath, wstring newSubFolderName)
{
	if (IsRootDirectoryW(folderPath))
	{
		int first = folderPath.find(L"\\");
		std::wstring newStr = folderPath.substr(0, first + 1);
		folderPath = newStr + newSubFolderName;
	}
	return folderPath;
}

wstring FolderCore::FolderBrowser(HWND m_hWnd)
{
	BROWSEINFO bi;
	bi.hwndOwner = m_hWnd;
	bi.pidlRoot = CSIDL_DESKTOP;//文件夹的根目录，此处为桌面
	bi.pszDisplayName = NULL;
	bi.lpszTitle = NULL;//显示位于对话框左上部的提示信息
	bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;//有新建文件夹按钮
	bi.lpfn = NULL;
	bi.iImage = 0;
	LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
	if (pidl == NULL)
	{
		return L"";
	}
	TCHAR strFolder[MAX_PATH];
	SHGetPathFromIDList(pidl, strFolder);

	std::wstring sFolder(strFolder);
	return sFolder;
}

wstring FolderCore::SetSHGetFolderPath(_In_ int csidl)
{
	TCHAR szPath[MAX_PATH];
	if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, szPath)))
	{
		wstring temp(szPath);
		return temp;
	}
	return L"";
}


void FolderCore::InitAppTempPath()
{
	//缓存路劲
	wchar_t strTmpDir[MAX_PATH] = { 0 };
	GetTempPathW(MAX_PATH, strTmpDir);
	wstring temp = strTmpDir;

	if (temp.empty() == false && temp != L"")
	{
		temp = temp + TempFolderName;//Temp缓存文件
	}
	else
	{
		temp = SetSHGetFolderPath(CSIDL_PERSONAL) + L"\\" + TempFolderName;//文档
	}
	BOOL isCreate = True;
	if (!PathIsDirectoryW(temp.c_str()))
		isCreate = CreateDirectory((temp.c_str()), NULL);

	if (isCreate == FALSE)
		temp = L"";

	/*temp = temp+L"\\";*/
// PathCore::smPath_Temp = AppCore::ReplaceSubStr(temp, L"\\", L"/");
	PathCore::smPath_Temp = temp;

	isCreate = True;
	//安装路径
	if (!PathIsDirectoryW(PathCore::smPath_Install.c_str()))
		isCreate = CreateDirectory((PathCore::smPath_Install.c_str()), NULL);

	if (isCreate)
	{
		PathCore::smPath_Install = PathCore::smPath_Install + L"\\" + Product::smName_Product;
		if (!PathIsDirectoryW(PathCore::smPath_Install.c_str()))
			isCreate = CreateDirectory((PathCore::smPath_Install.c_str()), NULL);

		PathCore::smPath_DefaultInstall = PathCore::smPath_Install;
	}
}

wstring FolderCore::GetAppTempPath()
{
	if (PathCore::smPath_Temp == L"")
	{
		PathCore::smPath_Temp = PathCore::smPath_Install;
	}
	return PathCore::smPath_Temp;
}

#include <io.h>
void FolderCore::ClearAllTempFolder()
{
	RemoveFolder(PathCore::smPath_Temp.c_str());

	wstring installPathFile = PathCore::smPath_Install + L"\\" + Product::smName_InstallPackage;
	DeleteFile(installPathFile.c_str());
}


void FolderCore::RemoveFolder(wstring path)
{
	WIN32_FIND_DATA FindFileData;
	wstring s = path + L"\\*.*";
	HANDLE hFind = FindFirstFile(s.c_str(), &FindFileData);
	if (INVALID_HANDLE_VALUE == hFind)
		return;

	do
	{
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			//Todo：暂时不遍历子目录，以下if语句是错的
			/*if (FindFileData.cFileName != _T(".") && FindFileData.cFileName != _T("."))
			{
				wstring subFolder = path + L"\\" + FindFileData.cFileName;
				RemoveFolder(subFolder);
			}*/
		}
		else
		{
			wstring file = path + L"\\" + FindFileData.cFileName;
			DeleteFile(file.c_str());
		}
	} while (FindNextFile(hFind, &FindFileData));
	//删除空文件夹：只对空文件夹有作用
	RemoveDirectory(path.c_str());
	FindClose(hFind);
}
#pragma endregion

#pragma region 磁盘
bool DiskCore::IsEnoughDisk(wstring smPath)
{
	auto cdDisk = smPath.substr(0, 1);
	std::wstring str_disk_name = cdDisk + L":\\";

	DWORD64 qwFreeBytesToCaller = 0;
	DWORD64 qwTotalBytes = 0;
	DWORD64 qwFreeBytes = 0;
	//获取磁盘信息
	BOOL bResult = GetDiskFreeSpaceExW(str_disk_name.c_str(),
		(PULARGE_INTEGER)&qwFreeBytesToCaller,//空闲空间（字节）
		(PULARGE_INTEGER)&qwTotalBytes,//磁盘总容量（字节）
		(PULARGE_INTEGER)&qwFreeBytes);//可获得的空闲空间（字节）

	if (bResult)
	{
		//可用空间是否足够1G时
		qwFreeBytesToCaller = qwFreeBytesToCaller / (1024 * 1024);
		if (Product::unFreeDiskMinSize > qwFreeBytesToCaller)
			return false;
	}
		return true;
}

wstring DiskCore::GetSystemDriveLetter()
{
	wchar_t str[MAX_PATH] = { 0 };
	GetSystemDirectoryW(str, MAX_PATH);
	wstring diskTag  = str;
	wstring disk;
	//避免获取不到系统盘符的可能，那就默认为C盘
	if (diskTag == L"")
	{
		disk = L"C";
	}
	else
	{
		disk = diskTag.substr(0, 1);
	}
	
	return disk;
}

//isDowndPackgeBefore：安装前。
bool DiskCore::IsMeetInstallPathMaxLength(bool isDowndPackgeBefore)
{
	if (isDowndPackgeBefore)
	{
		wstring installPathFolder = PathCore::smPath_Install + L"\\";
		if (installPathFolder.length() > Product::InstallPathMaxLength)
		{
			return false;
		}
	}
	else
	{
		wstring installPath = PathCore::smPath_Install + L"\\" + Product::smName_Application;
		if (FileCore::IsExistTheFileW(installPath) == false && installPath.length() > Product::InstallPathMaxLength)
		{
			return false;
		}
	}

	return true;
}
#pragma endregion
