import express from 'express';

/**
 * Asset controller plugin, граничен клас за обработка на заявките към игрови активи
 */
class AssetController{
    
    name = 'assetApi'
    route = '/asset'

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

        /**
         * API: GET /asset/:type/:id Retrieve asset by type and ID, извличане на актив по подаден идентификатор
         * @function read
         * @param {string} type Type can be "source", "default" or "thumb"
         * @param {string} id The name of the asset
         * @returns File
         * @memberof AssetController
         */
        router.get('/:where/:id(*)', async (req, res)=>{
            res.sendFile(config.fs.repo + req.params.where + '/' + req.params.id, (err)=>{
                if (err){
                    //console.error('Error retreiving file', req.params, err.code, err.message);
                    if (req.params.where == 'thumb'){
                        res.redirect(302, '/empty.png');
                    }else res.status(404).end();
                }
            });
        })

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

export {AssetController}