const _ = require('lodash');
const fetch = require('node-fetch');
const querystring = require('querystring');
const toObjectList = require('../toObjectList');
const log = require('../common/log');

function getStaff(req, res, orgId) {
    let options = Object.assign({}, convertRequestData(req), {
        page: req.params.page
    });

    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${orgId || req.params.org_id}/staff/`;

    Object.keys(options).forEach(key => {
        // не Boolean(options[key]), options[key] === 0 - ок
        if (options[key] === undefined || options[key] === null || options[key] === '')
            delete options[key];
    });

    if (Object.keys(options).length)
        requestUrl += '?' + querystring.stringify(options);

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(data => {
            if (data) {
                data.filter = options;
                data.result = toObjectList(req, data.result);
            }
            return data;
        })
        .then(data => addContainerDetails(req, res, orgId, data, options))
        .catch(error => {});
}

const OBJECT_TYPE_MAP = {
    users: 'user', departments: 'department', groups: 'group'
};

const USER_ROLE_MAP = {
    admins: 'admin', deputy_admins: 'deputy_admin'
};

const CONTAINER_TYPES = [ 'department', 'group' ];

function convertRequestData(req) {
    let { params, query } = req;
    let options = {};

    if (params.object_type) {
        let filterObject = {
            type: OBJECT_TYPE_MAP[params.object_type],
            id: params.object_id
        };

        if (filterObject.id && CONTAINER_TYPES.indexOf(filterObject.type) !== -1) {
            options.parent_type = filterObject.type;
            options.parent_id = filterObject.id;
        }
        else {
            options.type = filterObject.type;
            options.id = filterObject.id;
        }
    }

    if (params.service_slug)
        options['services.slug'] = params.service_slug;

    if (params.user_role) {
        options.type = 'user';
        options.role = USER_ROLE_MAP[params.user_role];
    }

    return _.assign(options, query);
}

function addContainerDetails(req, res, orgId, data, options) {
    if (!options || !options.parent_id || !options.parent_type)
        return data;

    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${orgId || req.params.org_id}/staff/?type=${options.parent_type}&id=${options.parent_id}`;

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(details => {
            if (details && details.result && details.result.length) {
                details.result = toObjectList(req, details.result);
                data = _.merge(data, { container: details.result[0] });
            }
            return data;
        })
        .catch(() => data);
}

module.exports = getStaff;
