'use strict';

const linz = require('../../../');

/**
 * Get the model name from a request.
 * @param {Object} req The HTTP request object.
 * @returns {String} The model name.
 */
const getModelFromRequest = (req) => {

    // The param is config for config routes and model for others.
    const { params = {} } = req;
    const model = params.model || params.config;

    if (model) {
        return model;
    }

    const modelMatch = req.path.match(/(?<=\/model\/)(\w*)(?<=\/\w*)/);

    // The match method returns null or an array of matches so we need to destructure it below.
    if (!modelMatch) {
        return null;
    }

    const [foundModel] = modelMatch;

    return foundModel;

};

/**
 * Set req.linz.model
 * @returns {Void} Calls the next middleware.
 */
const setLinzModel = () => (req, res, next) => {

    // The param is config for config routes and model for others.
    const model = getModelFromRequest(req);

    if (!model) {
        return next();
    }

    req.linz.model = linz.api.model.get(model);
    req.linz.model.linz.formtools.labels = linz.api.model.labels(model);

    linz.api.model.permissions(req.user, model, (err, permissions) => {

        if (err) {
            return next(err);
        }

        req.linz.model.linz.formtools.permissions = permissions;

        return next();

    });

};

module.exports = {
    getModelFromRequest,
    setLinzModel,
};

@@ -455,32 +455,15 @@
 h(/(
-?%3C=%5C/
 model%5C/
-)(%5Cw*)(?%3C=%5C/
 %5Cw*)
@@ -475,186 +475,128 @@
     
-// The match method returns null or an array of matches so we need to destructure it below.%0A    if (!modelMatch) %7B%0A        return null;%0A    %7D%0A%0A    const %5BfoundModel%5D = modelMatch
+if (!modelMatch) %7B%0A        return null;%0A    %7D%0A%0A    const %5Bpath%5D = modelMatch;%0A    const %5B_, modelName%5D = path.split('/')
 ;%0A%0A 
@@ -609,18 +609,17 @@
 urn 
-foundModel
+modelName
 ;%0A%0A%7D

fix for node 6