import {
	cleanFileName,
} from "qrc:/js/lib/utils";

/**
 * Builds a path string from the given options
 * @param cleanDir Name of the directory of the path
 * @param fileName Name of the file we want to create. If empty, only creates the cleanDir
 * @param extension Extension of the file
 * @returns string representing the path
 */
export function createPath(cleanDir: string, fileName: string, extension = ""): string {
	let result = cleanDir + "/" + cleanFileName(fileName, "_");
	if (extension && extension.length !== 0) {
		result += "." + cleanFileName(extension, "_");
	}
	return result;
}

/**
 * Create sub directories on demand and create symlink
 * @param targetPath The path we want to create.
 * @param cleanLinkDirPath The link that we want to targetPath
 * @param linkName Optional name of the link
 * @returns link path as a string if successful, undefined otherwise
 */
export function symlink(targetPath: string, cleanLinkDirPath: string, linkName = ""): string|undefined {
	if (!wsi4.io.fs.mkpath(cleanLinkDirPath)) {
		wsi4.util.error("symlink(): " + wsi4.util.translate("ErrorCreatingPath") + ": " + cleanLinkDirPath);
		return undefined;
	}
	let linkPath = cleanLinkDirPath;
	if (linkName.length > 0) {
		linkPath = createPath(linkPath, linkName);
	}
	if (!wsi4.io.fs.symlink(targetPath, linkPath)) {
		wsi4.util.error("symlink(): " + wsi4.util.translate("ErrorCreatingLink") + ": " + linkPath);
		return undefined;
	}
	return linkPath;
}

/**
 * Create sub directories on demand and write file
 * @param cleanDirPath Name of the directory of the path
 * @param fileName Name of the file we want to create. If empty, only creates the cleanDir
 * @param extension Extension of the file
 * @param data The data we want to write to the file
 * @returns string representing the path if successful, undefined otherwise
 */
export function writeFile(cleanDirPath: string, fileName: string, extension: string, data: ArrayBuffer): string|undefined {
	if (!wsi4.io.fs.mkpath(cleanDirPath)) {
		wsi4.util.error("writeFile(): " + wsi4.util.translate("ErrorCreatingPath") + ": " + cleanDirPath);
		return undefined;
	}
	const path = createPath(cleanDirPath, fileName, extension);
	if (!wsi4.io.fs.writeFile(path, data)) {
		wsi4.util.error("writeFile(): " + wsi4.util.translate("ErrorWritingFile"));
		return undefined;
	}
	return path;
}
