import cors from "cors";
import express from "express";
import { Request, Response } from "express";
import morgan from "morgan";
import fs from "fs";
import { generateKey } from "../util/key_factory";
import { GameStore } from "../game/gamestore/GameStore";

export class ExpressApp {
    app: Express.Application;
    gameStore: GameStore;
    constructor(params: { gameStore: GameStore }) {
        this.gameStore = params.gameStore;
        this.app = this.createExpressApp();
    }
    private createAccessLogMiddleware() {
        return morgan("common", {
            stream: fs.createWriteStream("./access.log", { flags: "a" }),
        });
    }
    public createExpressApp(): Express.Application {
        const app = express();
        app.use(cors());
        app.use(this.createAccessLogMiddleware());
        app.use(morgan("dev"));
        app.get("/", (req: Request, res: Response) => {
            res.send("Server up and running! ci test1");
        });
        app.get("/register/", (req: Request, res: Response) => {
            res.send(generateKey());
        });

        app.get("/game/:id", (req: Request, res: Response) => {
            const gameId = req.params.id;
            const game = this.gameStore.get(gameId);
            if(game) {
                res.send(game)
            } else {
                res.sendStatus(404)
            }
        });

        return app;
    }
}
