const _ = require('lodash');
const sendHandledRequest = require('../../lib/sendHandledRequest');

// query: { type: 'user' | 'department' | 'group' | 'service', id }
function send(req) {
    const prefix = req.query.id ? 'local_' : 'global_';

    return sendHandledRequest({
        method: 'get',
        url: [req.config.api.directory, 'permissions'],
        query: req.query,
        source: req,
        label: `read_${prefix}permissions`,
    });
}

function readService(req, res, next) {
    const originalQuery = _.clone(req.query);
    const requests = [];

    req.query = {};
    const globalPermissionsRequest = send(req);

    requests.push(globalPermissionsRequest);

    req.query = originalQuery;

    if (originalQuery.type) {
        const localPermissionsRequest = send(req).then(data => {
            const nextData = {};

            nextData.service = {};
            nextData.service[originalQuery.type] = data;

            return nextData;
        });

        requests.push(localPermissionsRequest);
    }

    return Promise.all(requests)
        .then(data => {
            if (!req.context.permissions) {
                req.context.permissions = {};
            }

            _.merge(req.context.permissions, {
                global: data[0],
                local: data[1],
            });

            return next ? next() : req;
        })
        .catch(next);
}

// Загрузка локальных прав
function readLocal(req, res, next) {
    const query = req.query;

    if (query.id && query.type) {
        return send(req)
            .then(data => {
                if (!req.context.permissions) {
                    req.context.permissions = {
                        local: {},
                    };
                }

                if (!req.context.permissions.local) {
                    req.context.permissions.local = {};
                }

                _.merge(req.context.permissions.local, {
                    [query.type]: {
                        [String(query.id)]: data,
                    },
                });

                return next ? next() : req;
            })
            .catch(next);
    }

    return Promise.resolve();
}

function read(req, res, next) {
    const originalQuery = _.clone(req.query);
    const requests = [];

    req.query = {};
    const globalPermissionsRequest = send(req);

    requests.push(globalPermissionsRequest);

    req.query = originalQuery;

    if (originalQuery.id && originalQuery.type) {
        const localPermissionsRequest = send(req).then(data => {
            // [ <permissions> ] > { "user": { "123": [ <permissions> ] } }
            const nextData = {};

            nextData[originalQuery.type] = {};
            nextData[originalQuery.type][String(originalQuery.id)] = data;

            return nextData;
        });

        requests.push(localPermissionsRequest);
    }

    return Promise.all(requests)
        .then(data => {
            if (!req.context.permissions) {
                req.context.permissions = {};
            }
            _.merge(req.context.permissions, {
                global: data[0],
                local: data[1],
            });

            return next ? next() : req;
        })
        .catch(next);
}

function readGlobal(req, res, next) {
    return send(req)
        .then(data => {
            if (!req.context.permissions) {
                req.context.permissions = {};
            }
            _.merge(req.context.permissions, {
                global: data,
            });

            return next ? next() : req;
        })
        .catch(next);
}

module.exports = {
    read,
    readGlobal,
    readLocal,
    readService,
};
