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 } = 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 = req.body;
                let object = await gameObject[data.id? 'update' : 'create'](req, data)
                res.json({status: 'OK', object});
            }catch(err){
                console.error(err);
                res.status(500).json({status: 'ERR', 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(req.body);
            res.json(result);
        })

        /**
         * 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);
        })

        /**
         * 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'});
        })

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

export {GameObjectsController}