const { Controller } = require('libflitter')

class LocaleController extends Controller {
    static get services() {
        return [...super.services, 'locale']
    }

    async resolve(req, res, next) {
        try {
            return res.api(req.T(req.params.resolver))
        } catch (e) {
            return res.status(400)
                .message(req.T('common.invalid_resolver'))
                .api()
        }
    }

    async load_module(req, res, next) {
        const resolver = `${req.i18n.region()}:${req.params.resolver}`
        try {
            return res.api(this.locale.get(resolver))
        } catch (e) {
            return res.status(400)
                .message(req.T('common.invalid_resolver'))
                .api()
        }
    }

    async batch_resolve(req, res, next) {
        if ( !req.body.resolvers || !Array.isArray(req.body.resolvers) )
            return res.status(400)
                .message(`${req.T('api.improper_field')} resolvers ${req.T('api.array')}`)
                .api()

        const translation_map = {}
        for ( const resolve of req.body.resolvers ) {
            translation_map[resolve] = req.T(resolve)
        }

        return res.api(translation_map)
    }
}

module.exports = exports = LocaleController
