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

const multipartMiddleware = multipart();

/**
 * GameObjectsController. API for the game objects manager, граничен клас за комуникация с модула за игрови обекти
 */
class GameObjectsController{
    
    name = 'gameObjectsApi'
    route = '/api/game-object'

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

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

        /**
         * API: POST /api/game-object/ List game objects by given criteria, търсене на обекти по критерии
         * @function list
         * @returns {GameObject[]}
         * @memberof GameObjectsController
         */
        router.post('/', async (req, res)=>{
            let result = await gameObject.list(db.sanitizeQuery(req.body));
            res.json(result);
            am.audit(req, `game-object-list`, null, {q: req.body});
        })

        router.post('/tags', async (req, res)=>{
            let tags = await gameObject.getTags(req.body.q);
            res.json(tags);
        })

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

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

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

export {GameObjectsController}