import fs from "fs";
import { Game } from "@mancala/core";
import { BackendGame } from "../models/Game";
const crashFolder = "./crashes";
export class GameCrashManager {
  constructor() {}

  static createCrashFolderIfNotExist(): void {
    if (!fs.existsSync(crashFolder)) {
      fs.mkdirSync(crashFolder);
    }
  }

  static getTime(): string {
    let date_ob = new Date();
    let date = ("0" + date_ob.getDate()).slice(-2);
    let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
    let year = date_ob.getFullYear();
    let hours = date_ob.getHours();
    let minutes = date_ob.getMinutes();
    let seconds = date_ob.getSeconds();
    let miliSeconds = date_ob.getMilliseconds();
    return `${year}-${month}-${date}-${hours}:${minutes}:${seconds}:${miliSeconds}`;
  }

  public static logGameCrash(error: Error, game: BackendGame): string {
    this.createCrashFolderIfNotExist();
    const crash = {
      message: error.message,
      stack: error.stack,
      game,
    };
    const crashStr = JSON.stringify(crash);
    const crashFileName = `${game.id}::${this.getTime()}`;
    fs.writeFile(`${crashFolder}/${crashFileName}`, crashStr, () => {});
    return crashFileName;
  }
}
