import haxe.macro.Expr.Catch;
import Sys;
import sys.FileSystem;

class Main {

	static var dir: String = "C:\\Users\\Eero\\AppData\\Local\\Temp";

	static function main() {
		clean(dir);
	}

	static function deleteFile(path) {
		var stat = FileSystem.stat(path);
		if(stat.size == 0){
			try {

				Sys.println("Deleting file: "+path);
				FileSystem.deleteFile(path);
			} catch(e: Any) {
				Sys.println("Could not delete file: "+path);
			}
			
		}
	}

	static function deleteDirectory(path) {
		if(!FileSystem.isDirectory(path))
			return false;

		for (e in FileSystem.readDirectory(path)){
			var temp = path+"/"+e;
			if(!FileSystem.isDirectory(temp))
				continue; // Go next
			try {
				if(FileSystem.readDirectory(temp).length == 0){
					Sys.println("Deleting directory: "+temp);
					FileSystem.deleteDirectory(temp);
				} else if (FileSystem.readDirectory(temp).length != 0){
					deleteDirectory(temp);
				} else if(!FileSystem.isDirectory(temp)){
					deleteFile(temp);
				}
			} catch(e: SysError){
				Sys.println("Failed: Cannot access directory " + temp);
			}
		}
		return true;
	}

	static function clean(path: String) {
		if(FileSystem.exists(path) && FileSystem.isDirectory(path)){
			deleteDirectory(path);
			// for (e in FileSystem.readDirectory(path)){
			// 	var temp = path+"/"+e;
			// 	try {
			// 		if(FileSystem.isDirectory(temp) && FileSystem.readDirectory(temp).length == 0){
			// 			Sys.println("Deleting directory: "+temp);
			// 			FileSystem.deleteDirectory(temp);
			// 		} else if (FileSystem.isDirectory(temp) && FileSystem.readDirectory(temp).length != 0) {
			// 			for(ent in FileSystem.readDirectory(temp)){
			// 				var subDir = temp+"/"+ent;
			// 				// Sys.println(subDir);
			// 				clean(subDir);
			// 			}
						
			// 		} else if(!FileSystem.isDirectory(temp)){
			// 			deleteFile(temp);
			// 		}
			// 	} catch(e: SysError){
			// 		Sys.println("Failed: Cannot access directory " + temp);
			// 	}

			// 	// pathData.push(Sha256.encode(temp));
			// 	// readDirectory(temp);
			// }
		} else if(FileSystem.exists(path) && !FileSystem.isDirectory(path)){
			deleteFile(path);
		}

	}
}
