import type { Moment } from "moment" ; import moment from "moment" ; import path from "path" ; import type { WritableOptions } from "stream" ; import { Command } from "../types" ; import { SlpFile } from "./slpFile" ; import type { SlpRawEventPayload , SlpStreamSettings } from "./slpStream" ; import { SlpStream , SlpStreamEvent } from "./slpStream" ; /**
 * The default function to use for generating new SLP files.
 */ function getNewFilePath ( folder , m ) { return path . join ( folder , `Game_${ m . format ( "YYYYMMDD" ) }T${ m . format ( "HHmmss" ) }.slp` ) ; } export interface SlpFileWriterOptions extends Partial < SlpStreamSettings > { outputFiles : boolean ; folderPath : string ; consoleNickname : string ; newFilename : ( folder : string , startTime : Moment ) => string ; } const defaultSettings = { outputFiles : true , folderPath : "." , consoleNickname : "unknown" , newFilename : getNewFilePath , } ; export enum SlpFileWriterEvent { NEW_FILE = "new-file" , FILE_COMPLETE = "file-complete" } export class extends SlpStream export class SlpFileWriter extends SlpStream { private currentFile : SlpFile | null = null ; private options : SlpFileWriterOptions ; /**
     * Creates an instance of SlpFileWriter.
     */ public constructor ( options ? , opts ? ) { super ( options , opts ) ; this . options = Object . assign ( { } , defaultSettings , options ) ; this . _setupListeners ( ) ; } private _writePayload ( payload ) { if ( this . currentFile ) { this . currentFile . write ( payload ) ; } } private _setupListeners ( ) { this . on ( SlpStreamEvent . RAW , ( data ) => { const { command , payload } = data ; switch ( command ) { case Command . MESSAGE_SIZES : this . _handleNewGame ( ) ; this . _writePayload ( payload ) ; break ; case Command . GAME_END : this . _writePayload ( payload ) ; this . _handleEndGame ( ) ; break ; default : this . _writePayload ( payload ) ; break ; } } ) ; } returns { ( string | null ) } memberof public getCurrentFilename ( ) { if ( this . currentFile !== null ) { return path . resolve ( this . currentFile . path ( ) ) ; } return null ; } returns { ( string | null ) } memberof public endCurrentFile ( ) { this . _handleEndGame ( ) ; } param { Partial < SlpFileWriterOptions > } settings memberof public updateSettings ( settings ) { this . options = Object . assign ( { } , this . options , settings ) ; } private _handleNewGame ( ) { if ( this . options . outputFiles ) { const filePath = this . options . newFilename ( this . options . folderPath , moment ( ) ) ; this . currentFile = new SlpFile ( filePath , this ) ; this . emit ( SlpFileWriterEvent . NEW_FILE , filePath ) ; } } private _handleEndGame ( ) { if ( this . currentFile ) { this . currentFile . setMetadata ( { consoleNickname : this . options . consoleNickname , } ) ; this . currentFile . end ( ) ; this . emit ( SlpFileWriterEvent . FILE_COMPLETE , this . currentFile . path ( ) ) ; this . currentFile = null ; } } }