import type { AeroflyFlight } from "@fboes/aerofly-custom-missions"; import type { Config } from "./Config.js"; import fs from "node:fs"; import path from "node:path"; import { AeroflyFileParser } from "../converter/parser/AeroflyFileParser.js"; import { AeroflyMainConfigParser } from "../converter/parser/AeroflyMainConfigParser.js"; export class AeroflyMainConfigReaderError extends Error { constructor( message: string, public readonly code: "MISSING_SETUP" = "MISSING_SETUP", ) { super(message); this.name = this.constructor.name; } } /** * Reader to convert `main.mcf` file into `AeroflyFlight` class instance. */ export class AeroflyMainConfigReader { constructor(private config: Config) {} get mainCfgFileName() { if (!this.config.mainMcfFilePath) { throw new AeroflyMainConfigReaderError("mainMcfFilePath is not defined in the config."); } if (!fs.existsSync(this.config.mainMcfFilePath)) { throw new AeroflyMainConfigReaderError( `The specified mainMcfFilePath does not exist: ${this.config.mainMcfFilePath}`, ); } const filename = path.join(this.config.mainMcfFilePath, "main.mcf"); if (!fs.existsSync(filename)) { throw new AeroflyMainConfigReaderError(`The main.cfg does not exists at ${filename}`); } return filename; } read(): AeroflyFlight { const mainMcfContent = fs.readFileSync(this.mainCfgFileName, "utf-8"); return this.parseMainMcf(mainMcfContent); } parseMainMcf(mainMcfContent: string): AeroflyFlight { const parser = new AeroflyMainConfigParser(); return parser.parse(mainMcfContent); } write(flight: AeroflyFlight): void { // Open the main.mcf file let mainMcfContent = fs.readFileSync(this.mainCfgFileName, "utf-8"); // Replace the appropriate sections with the data from the AeroflyFlight object const parser = new AeroflyFileParser(); mainMcfContent = parser.setGroup( mainMcfContent, "tmsettings_aircraft", 2, flight.aircraft.getElement().toString(2), ); mainMcfContent = parser.setGroup( mainMcfContent, "tmsettings_flight", 2, flight.flightSetting.getElement().toString(2), ); mainMcfContent = parser.setGroup(mainMcfContent, "tm_time_utc", 2, flight.timeUtc.getElement().toString(2)); mainMcfContent = parser.setGroup(mainMcfContent, "tmsettings_wind", 2, flight.wind.getElement().toString(2)); mainMcfContent = parser.setGroup(mainMcfContent, "tmsettings_clouds", 2, flight.getCloudsElement().toString(2)); mainMcfContent = parser.setGroup( mainMcfContent, "tmnavigation_config", 2, flight.navigation.getElement().toString(2), ); mainMcfContent = parser.setGroup( mainMcfContent, "tmsettings_fuel_load", 2, flight.fuelLoadSetting.getElement().toString(2), ); mainMcfContent = parser.setNumber(mainMcfContent, "visibility", flight.visibility); // Save the modified content back to the main.mcf file fs.writeFileSync(this.mainCfgFileName, mainMcfContent, "utf-8"); } }