const _ = require('lodash');
const user = require('./user');
const group = require('./group');
const permissions = require('./permissions');

const GROUP_LIST_PARAMS = ['type', 'admin_uid', 'member_uid', 'page', 'per_page'];

function readList(req, res, next) {
    let request;

    // запрос списка команд, в которых пользователь 'member_uid' - участник
    // FIXME: добавить фильтр 'member_uid' в API Директории (DIR-4546)
    if (req.query.member_uid) {
        const originalQuery = _.clone(req.query);

        req.query = {
            id: originalQuery.member_uid,
        };

        // запрашиваем информацию о пользователе, чтобы получить список команд,
        // в которых он состоит
        request = user.read(req)
            .then(nextReq => {
                const contextUser = _.find(nextReq.context.users, {
                    id: Number(originalQuery.member_uid),
                });
                const userGroups = (contextUser ? contextUser.groups : null) || [];

                if (!userGroups.length) {
                    return nextReq;
                }

                nextReq.query = _.pick(originalQuery, GROUP_LIST_PARAMS);
                nextReq.query.id = userGroups.map(item => item.id).join(',');

                return group.readList(nextReq);
            });
    } else {
        request = group.readList(req);
    }

    return request
        .then(nextReq => next ? next() : nextReq)
        .catch(next);
}

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

    if (originalQuery.id) {
        req.query = {
            id: originalQuery.id,
        };

        const groupRequest = group.read(req);

        requests.push(groupRequest);
    }

    if (!originalQuery.id || originalQuery.extension === 'deep') {
        req.query = _.pick(originalQuery, GROUP_LIST_PARAMS);

        if (originalQuery.ids) {
            req.query.id = originalQuery.ids;
        }

        const groupListRequest = readList(req);

        requests.push(groupListRequest);
    }

    if (originalQuery.extension) {
        req.query = {
            id: originalQuery.id,
            type: 'group',
        };

        const permissionsRequest = permissions.read(req);

        requests.push(permissionsRequest);
    }

    return Promise.all(requests)

        /*
        .then(() => {
            req.query = originalQuery;
            return readNestedSubsection(req);
        })
        */
        .then(nextReq => next ? next() : nextReq)
        .catch(next);
}

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

    const groupRequest = group.read(req);

    requests.push(groupRequest);

    req.query = {
        recursive_group_id: originalQuery.id,
    };

    const userListRequest = user.readList(req);

    requests.push(userListRequest);

    if (originalQuery.extension && originalQuery.id) {
        req.query = {
            id: originalQuery.id,
            type: 'group',
        };

        const permissionsRequest = permissions.read(req);

        requests.push(permissionsRequest);
    }

    return Promise.all(requests)
        .then(nextReq => next ? next() : nextReq)
        .catch(next);
}

/*
function readNestedSubsection(req) {
    var originalQuery = _.clone(req.query);

    if (originalQuery['user_id']) {
        req.query = {
            id: originalQuery['user_id']
        };
        return user.read(req);
    }

    if (originalQuery['department_id']) {
        req.query = {
            'recursive_department_id': originalQuery['department_id']
        };
        return user.readList(req);
    }

    if (originalQuery['group_id']) {
        req.query = {
            'recursive_group_id': originalQuery['group_id']
        };
        return user.readList(req);
    }

    return req;
}
*/

module.exports = _.extend({}, group, { readList, read, readFlat });
