import {StoreComponent} from "../StoreComponent"; import {FileUtils} from "../FileUtils"; import * as path from "node:path"; import * as fs from "fs"; export class GamesystemStorage { private gamesystemRootDir: string constructor(gamesystemRootDir: string) { this.gamesystemRootDir = gamesystemRootDir; FileUtils.prepareDirectoryFroWriting(gamesystemRootDir) } public storeGamesystems(gamesystems: StoreComponent[]) { const unreferencedFiles = this.detectUnusedGamesystemFiles(gamesystems) FileUtils.removeFiles(unreferencedFiles) gamesystems.forEach(gamesystem => this.storeGamesystem(gamesystem)) } private detectUnusedGamesystemFiles(gamesystems: StoreComponent[]) { const unreferencedFiles: string[] = [] const gamesystemFiles = FileUtils.listFilesInDirectory(this.gamesystemRootDir); while(gamesystemFiles.length > 0) { const currentGamesystemFile = gamesystemFiles.shift() const referencedGamesystemName = path.parse(path.basename(currentGamesystemFile!)).name const referencedGamesystem = this.findReferencedGamesystem(referencedGamesystemName, gamesystems) if(referencedGamesystem == undefined) { unreferencedFiles.push(currentGamesystemFile!) } else { const decodedJSONData = JSON.parse(referencedGamesystem!.jsonString) if(decodedJSONData.childsystems != undefined) { //Check if current file is a directory. When it is a directory, everything is fine if(fs.lstatSync(currentGamesystemFile!).isDirectory()) { } else { const parentDirName = path.basename(path.dirname(currentGamesystemFile!)) if(parentDirName !== referencedGamesystemName) { unreferencedFiles.push(currentGamesystemFile!) } } } } if(fs.lstatSync(currentGamesystemFile!).isDirectory()) { gamesystemFiles.push(... FileUtils.listFilesInDirectory(currentGamesystemFile!)) } } return unreferencedFiles; } private findReferencedGamesystem(referencedName: string, gamesystems: StoreComponent[]): StoreComponent | undefined { return gamesystems.find(gamesystem => path.basename(gamesystem.fileName) === referencedName) } private storeGamesystem(gamesystem: StoreComponent) { const gamesystemFile = path.join(... gamesystem.fileName.split("/")) const completeGamesystemFile = path.join(this.gamesystemRootDir, gamesystemFile) FileUtils.prepareFileForWriting(completeGamesystemFile) fs.writeFileSync(completeGamesystemFile + ".json", gamesystem.jsonString, 'utf-8') } }