import express from 'express';
import multipart from 'connect-multiparty';

const multipartMiddleware = multipart();

/**
 * GamesController. API for the games manager, граничен клас за комуникация с модула за игрови дефиниции
 */
class GamesController{
    
    name = 'gamesApi'
    route = '/api/game'

    /**
     * Initializes the GamesController plugin, инициализация
     * @param {App} app The application instance, апликация
     */
    init(app){
        const router = express.Router();
        const { game, am } = app;

        /**
         * API: PUT /api/game/ Create or update game, създаване/обновяване на игрова дефиниция
         * @function createOrUpdate
         * @memberof GamesController
         */
        router.put('/', async (req, res)=>{
            try{
                let data = req.body;
                let action = data.id ? 'update' : 'create';
                let object = await game[action](req, data)
                res.json({status: 'OK', object});
                am.audit(req, `game-${action}`, object.id);
            }catch(err){
                console.error(err);
                res.status(500).json({status: 'ERR', err});
                am.audit(req, `game-alter-error`, req.body?.id, {q: req.body, e: err});
            }
        });

        router.post('/:id/header', multipartMiddleware, async (req, res)=>{
            try{
                let id = parseInt(req.params.id);                
                await game.setHeader(req, id, req.files.file);
                res.json({status: 'OK'});
                am.audit(req, `game-header-set`, id);
            }catch(err){
                console.error(err);
                res.status(500).json({status: 'ERR', err});
                am.audit(req, `game-header-error`, id, {e: err});
            }
        });

        /**
         * API: POST /api/game/ List games by given criteria, търсене в игрови дефиниции
         * @function list
         * @returns {Game[]}
         * @memberof GamesController
         */
        router.post('/', async (req, res)=>{
            let result = await game.list(req.body);
            res.json(result);
            am.audit(req, `game-list`, null, {q: req.body});
        })

        /**
         * API: GET /api/game/:id Retrieve game by ID, извличане на игрова дефиниция
         * @function read
         * @param {string} id The id of the game, идентификатор на дефиницията
         * @returns {Game}
         * @memberof GamesController
         */
        router.get('/:id', async (req, res)=>{
            let object = await game.read(parseInt(req.params.id));
            res.json(object);
            am.audit(req, `game-read`, object.id);
        })

        /**
         * API: DELETE /api/game/:id Delete game by ID, изтриване на игрова дефиниция
         * @function remove
         * @param {string} id The id of the game, идентификатор на дефиницията
         * @memberof GamesController
         */
        router.delete('/:id', async (req, res)=>{
            await game.remove(req.params.id);
            res.json({status: 'OK'});
            am.audit(req, `game-delete`, req.params.id);
        })

        app.webServer.xapp.use(this.route, router);
    }
}

export { GamesController }