const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec
let ifFile = true;
exports.getAppPath = () => {
	if (ifFile == false) {
		return;
	}
	let path = __dirname;
	path = path.replaceAll("\\", "/");
	const lastIndex = path.lastIndexOf('/modules');
	if (lastIndex !== -1) {
		const beforeModules = path.slice(0, lastIndex);
		const afterModules = '/DataHtml';
		path = beforeModules + afterModules;
	}
	return path;
}
exports.getDesktop = () => {
	if (ifFile == false) {
		return;
	}
	if (process.platform == 'darwin') {
		return process.env.HOME + "/Desktop"
	}
	if (process.platform == 'linux') {
		return process.env.HOME
	}
	let path_ = process.env.USERPROFILE + "/Desktop"
	path_ = path_.replaceAll("\\", "/")
	return path_;
}
exports.getPathAll = () => {
	if (ifFile == false) {
		return;
	}
	return process.env
}
/**
 * 遍历文件夹所有文件
 * @dirPath 文件夹路径
 * @mode 0(默认)=按级输出，1=所有文件输出到同一级
 * @pathMode 0(默认)=绝对路径，1=仅文件名
 */
exports.listFile = async (dirPath, funEv = undefined) => {
	if (ifFile == false) {
		return;
	}
	try {
		listFile_(dirPath).then(res => {
			if (funEv != undefined) {
				let PathArr = output(res, 0)
				for (let index = 0; index < PathArr.length; index++) {
					PathArr[index] = PathArr[index].replace("-- ", "")
				}
				funEv(PathArr);
			}
		});
	} catch (err) {
		if (funEv != undefined) {
			funEv([]);
		}
	}
}
// 监视指定目录中的文件变化
exports.watch = (dirPath, funEv = undefined) => {
	if (ifFile == false) {
		return;
	}
	try {
		fs.watch(dirPath, (eventType, filename) => {
			if (filename) {
				if (funEv != undefined) {
					funEv({
						"事件类型": eventType,
						"改变名称": filename
					})
				}
			}
		});
	} catch (err) {

	}
}
const listFile_ = async (dirPath, mode = 1, pathMode = 0) => {
	return await listDir(dirPath, mode, pathMode);
}
const listDir = async (dirPath, mode, pathMode) => {
	try {
		var res = new Array();
		const files = await fs.readdirSync(dirPath, { withFileTypes: true });
		for (const file of files) {
			const name = file.name;
			if (!file.isDirectory()) {
				let fileName = pathMode ? name : path.resolve(dirPath, name);
				res.push(fileName);
			}
			else {
				let value;
				await listDir(path.resolve(dirPath, name), mode, pathMode).then(res => { value = res });
				if (mode == 1) {
					for (let i = 0; i < value.length; i++)
						res.push(value[i]);
				} else {
					let dir = {};
					let dirName = pathMode ? name : path.resolve(dirPath, name);
					dir[dirName] = value;
					res.push(dir);
				}
			}
		}
		return res;
	} catch (err) {
		return null;
	}
}
function output(array, level) {
	let logFile = [];
	for (let i = 0; i < array.length; i++) {
		const item = array[i];
		let levelChar = '';
		for (let j = 0; j < level; j++) levelChar += '  ';
		levelChar += '-- ';
		if (!(item instanceof Object)) {
			logFile[logFile.length] = levelChar + item
		} else {
			const dirName = Object.keys(item)[0];
			const dirArray = Object.values(item)[0];
			logFile[logFile.length] = levelChar + dirName
			output(dirArray, level + 1);
		}
	}
	return logFile
}
exports.getExe = () => {
	if (ifFile == false) {
		return;
	}
	let pathAll = process.execPath;
	pathAll = pathAll.replaceAll("\\", "/");
	if (process.platform !== 'darwin') {
		pathAll = pathAll.split("/");
		if (pathAll.length >= 1) {
			pathAll = pathAll[pathAll.length - 1]
			pathAll = "/" + pathAll
			pathAll = process.execPath.substring(0, process.execPath.length - pathAll.length)
		} else {
			pathAll = process.execPath
		}
	} else {
		pathAll = pathAll.split("/Contents/Frameworks/Electron Helper (Renderer).app");
		if (pathAll.length >= 1) {
			pathAll = pathAll[pathAll.length - 1]
			pathAll = "/Contents/Frameworks/Electron Helper (Renderer).app" + pathAll
			pathAll = process.execPath.substring(0, process.execPath.length - pathAll.length)
			let pathAll2 = pathAll.split("/");
			if (pathAll2.length >= 1) {
				pathAll2 = pathAll2[pathAll2.length - 1]
				pathAll = pathAll.substring(0, pathAll.length - pathAll2.length)
			}
		} else {
			pathAll = process.execPath
		}
	}
	return pathAll;
}
exports.existsSync = (path) => {
	if (ifFile == false) {
		return;
	}
	try {
		return fs.existsSync(path);
	} catch (err) {
		return false;
	}
}
exports.writeFileSync = (data) => {
	if (ifFile == false) {
		return;
	}
	try {
		fs.writeFileSync(data["路径"], data["数据"]);
		return true;
	} catch (err) {
		return false;
	}
}
exports.writeFileBase64Sync = (data) => {
	if (ifFile == false) {
		return;
	}
	try {
		var b = new Buffer.from(data["数据"], 'base64')
		fs.writeFileSync(data["路径"], b);
		return true;
	} catch (err) {
		return false;
	}
}

exports.writeFileHexSync = (data) => {
	if (ifFile == false) {
		return;
	}
	try {
		var b = new Buffer.from(data["数据"], 'hex')
		fs.writeFileSync(data["路径"], b);
		return true;
	} catch (err) {
		return false;
	}
}
exports.readFileSync = (data) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(data["路径"]) == true) {
		if (data["编码"] == undefined) {
			data["编码"] = "utf8";
		}
		try {
			if (data["编码"] == "") {
				return fs.readFileSync(data["路径"]);
			} else {
				return fs.readFileSync(data["路径"], data["编码"]);
			}
		} catch (err) {
			return "";
		}

	} else {
		return "";
	}
}
exports.readFileBase64Sync = (data) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(data["路径"]) == true) {
		try {
			let File = fs.readFileSync(data["路径"]);
			return Buffer.from(File).toString('base64');
		} catch (err) {
			return "";
		}
	} else {
		return "";
	}
}
exports.readFileHexSync = (data) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(data["路径"]) == true) {
		try {
			let File = fs.readFileSync(data["路径"]);
			return Buffer.from(File).toString('hex');
		} catch (err) {
			return "";
		}
	} else {
		return "";
	}
}
exports.mkdirSync = (path) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(path) == true) {
		return true;
	} else {
		try {
			fs.mkdirSync(path);
			return true;
		} catch (err) {
			return false
		}

	}
}
exports.cp = (path, path2, funEv = undefined) => {
	if (ifFile == false) {
		return;
	}
	fs.cp(path, path2, { recursive: true }, (err) => {
		if (err) {
			if (funEv != undefined) {
				funEv({ "状态": "失败", "数据": err })
			}
		} else {
			if (funEv != undefined) {
				funEv({ "状态": "成功" })
			}
		}
	});
}
exports.renameSync = (data) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(data["路径"]) == true) {
		try {
			fs.renameSync(data["路径"], data["路径2"])
			return true;
		} catch (err) {
			return false
		}
	} else {
		return false;
	}
}
exports.unlink = (path, funEv = undefined) => {
	if (ifFile == false) {
		return;
	}
	if (fs.existsSync(path)) {
		if (path.indexOf(".") == -1) {
			ExeFun_unlinkFile(path, (ret) => {
				if (funEv != undefined) {
					funEv(ret)
				}
			})
			return;
		}
		fs.unlink(path, (err) => {
			if (err) {
				if (funEv != undefined) {
					funEv({ "状态": "删除失败", "原因": err })
				}
			} else {
				if (funEv != undefined) {
					funEv({ "状态": "删除成功" })
				}
			}
		});
	} else {
		funEv({ "状态": "删除失败", "原因": "路径不存在" })
	}
}

exports.appendFile = (data) => {
	if (ifFile == false) {
		return;
	}
	fs.appendFile(data["路径"], data["数据"], (err) => {
		if (err) throw err;
	});
}
exports.basename = (path_) => {
	if (ifFile == false) {
		return;
	}
	return path.basename(path_);
}
exports.dirname = (path_) => {
	return path.dirname(path_);
}
exports.extname = (path_) => {
	if (ifFile == false) {
		return;
	}
	return path.extname(path_);
}
exports.isAbsolute = (path_) => {
	if (ifFile == false) {
		return;
	}
	return path.isAbsolute(path_);
}
exports.normalize = (path_) => {
	if (ifFile == false) {
		return;
	}
	return path.normalize(path_);
}
exports.FileMsg = (path, EvFun) => {
	if (ifFile == false) {
		return;
	}
	fs.stat(path, function (error, stats) {
		let FileMsg = {
			"占用空间": 0,
			"实际大小": 0,
			"访问时间戳": 0,
			"访问时间": "",
			"修改时间戳": 0,
			"修改时间": "",
			"创建时间戳": 0,
			"创建时间": "",
			"是否成功": false
		};
		if (error) {
			if (EvFun != undefined) {
				EvFun(FileMsg)
			}
		} else {
			FileMsg["占用空间"] = stats.blksize;
			FileMsg["实际大小"] = stats.size;
			FileMsg["访问时间戳"] = stats.atimeMs;
			FileMsg["访问时间"] = stats.atime;
			FileMsg["修改时间戳"] = stats.ctimeMs;
			FileMsg["修改时间"] = stats.ctime;
			FileMsg["创建时间戳"] = stats.birthtimeMs;
			FileMsg["创建时间"] = stats.birthtime;
			FileMsg["是否成功"] = true;
			if (EvFun != undefined) {
				EvFun(JSON.stringify(FileMsg))
			}
		}
	})
}
function deleteDirRecursively(dirPath) {
	return new Promise((resolve, reject) => {
		fs.readdir(dirPath, (err, files) => {
			if (err) {
				return reject(err);
			}
			let pending = files.length;
			if (pending === 0) {
				// 如果没有文件或子目录，则直接删除目录  
				return fs.rmdir(dirPath, err => {
					if (err) {
						return reject(err);
					}
					resolve();
				});
			}
			files.forEach(file => {
				const filePath = path.join(dirPath, file);
				fs.stat(filePath, (err, stat) => {
					if (err) {
						return reject(err);
					}
					if (stat.isDirectory()) {
						// 如果是目录，则递归删除  
						deleteDirRecursively(filePath).then(() => {
							if (--pending === 0) {
								// 所有子目录和文件都删除后，删除当前目录  
								fs.rmdir(dirPath, err => {
									if (err) {
										return reject(err);
									}
									resolve();
								});
							}
						}).catch(reject);
					} else {
						// 如果是文件，则删除  
						fs.unlink(filePath, err => {
							if (err) {
								return reject(err);
							}
							if (--pending === 0) {
								// 所有文件都删除后，删除目录  
								fs.rmdir(dirPath, err => {
									if (err) {
										return reject(err);
									}
									resolve();
								});
							}
						});
					}
				});
			});
		});
	});
}
function ExeFun_unlinkFile(P_Name, fun) {
	if (P_Name == undefined || P_Name == null) {
		fun({ "状态": "失败", "原因": "删除失败,路径不能为未定义内容或空对象" })
		return;
	}
	if (P_Name.indexOf("\\") != -1) {
		P_Name = P_Name.replaceAll("\\", "/")
	}
	if (P_Name.indexOf("//") != -1) {
		P_Name = P_Name.replaceAll("//", "/")
	}
	var stat = fs.lstatSync(P_Name);
	if (stat.isFile() == true) {
		//文件
		fs.unlink(P_Name, (err) => {
			if (err) {
				fun({ "状态": "失败", "原因": err })
				return;
			}
			fun({ "状态": "成功" })
		});
	} else {
		deleteDirRecursively(P_Name)
			.then(() => fun({ "状态": "成功" }))
			.catch(err => fun({ "状态": "失败", "原因": err }));
	}
}
function runExec_(Path, cmdCode, SetProcessYesMsg, SetProcessNoMsg, SetProcessEndMsg, encoding_ = "GBK") {
	let workerProcess;//子进程名称
	workerProcess = exec(cmdCode, { cwd: Path, encoding: encoding_ })
	// 打印正常的后台可执行程序输出
	workerProcess.stdout.on('data', function (data) {
		const decoder = new TextDecoder();
		let JSONData = { "输出数据": decoder.decode(data) }
		if (SetProcessYesMsg != undefined) {
			SetProcessYesMsg(JSONData)
		}
	})
	// 打印错误的后台可执行程序输出
	workerProcess.stderr.on('data', function (data) {
		const decoder = new TextDecoder();
		let JSONData = { "输出数据": decoder.decode(data) }
		if (SetProcessNoMsg != undefined) {
			SetProcessNoMsg(JSONData)
		}
	})
	// 退出之后的输出
	workerProcess.on('close', function (code) {
		if (SetProcessEndMsg != undefined) {
			SetProcessEndMsg(code)
		}
	})
}
//electronPreloadBegin
if (window.FOFStudioSizeFileAll) {
	const { ipcRenderer } = require('electron')
	let keyArr = ArrObjKey(window.FOFStudioSizeFileAll);
	let path = __dirname;
	path = path.replaceAll("\\", "/");
	path = path.replaceAll("app/modules", "app/DataHtml/");
	for (let index = 0; index < keyArr.length; index++) {
		if (window.FOFStudioSizeFileAll[keyArr[index]]) {
			try {
				let path_ = "";
				if (window.FOFStudioSizeFileAll[keyArr[index]]["Type"] == "javascript") {
					path_ = "javascript/"
				}
				if (window.FOFStudioSizeFileAll[keyArr[index]]["Type"] == "css") {
					path_ = "css/"
				}
				if (window.FOFStudioSizeFileAll["type"] == 1) {
					if (window.FOFStudioSizeFileAll[keyArr[index]]["name"].indexOf(".html") == -1) {
						if (fs.existsSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"]) == true) {
							let data = fs.readFileSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"], "utf8");
							if (data.length != window.FOFStudioSizeFileAll[keyArr[index]]["大小"]) {
								ifFile = false;
								ipcRenderer.invoke('destroy', "")
							}
						}
					}
				}
				if (window.FOFStudioSizeFileAll["type"] == 2) {
					if (window.FOFStudioSizeFileAll[keyArr[index]]["name"].indexOf(".css") == -1) {
						if (fs.existsSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"]) == true) {
							let data = fs.readFileSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"], "utf8");
							if (data.length != window.FOFStudioSizeFileAll[keyArr[index]]["大小"]) {
								ifFile = false;
								ipcRenderer.invoke('destroy', "")
							}
						}
					}
				}
				if (window.FOFStudioSizeFileAll["type"] == 3) {
					if (window.FOFStudioSizeFileAll[keyArr[index]]["name"].indexOf(".js") == -1) {
						if (fs.existsSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"]) == true) {
							let data = fs.readFileSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"], "utf8");
							if (data.length != window.FOFStudioSizeFileAll[keyArr[index]]["大小"]) {
								ifFile = false;
								ipcRenderer.invoke('destroy', "")
							}
						}
					}
				}
				if (window.FOFStudioSizeFileAll["type"] == 4) {
					if (fs.existsSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"]) == true) {
						let data = fs.readFileSync(path + path_ + window.FOFStudioSizeFileAll[keyArr[index]]["name"], "utf8");
						if (data.length != window.FOFStudioSizeFileAll[keyArr[index]]["大小"]) {
							ifFile = false;
							ipcRenderer.invoke('destroy', "")
						}
					}
				}
			} catch (error) {

			}
		}
	}
	try {
		if (window.FOFStudioSize) {
			if (window.FOFStudioSize[2]) {
				path = path.replaceAll("app/DataHtml/", "app/");
				if (fs.existsSync(path + "preload.js") == true) {
					let data = fs.readFileSync(path + "preload.js", "utf8");
					if (data.length != window.FOFStudioSize[2]) {
						ipcRenderer.invoke('destroy', "")
						ifFile = false;
					}
				}
			}
		}
	} catch (error) {

	}
}
function ArrObjKey(obj) {
	let retarr = [];
	for (let data in obj) {
		retarr[retarr.length] = data;
	}
	return retarr;
}
//electronPreloadEnd