const _ = require('lodash');

const ENTITY_TYPE_MAP = {
    users: 'user',
    departments: 'department',
    groups: 'group',
    organizations: 'organization',
    sessions: 'session',
};

const FILTER_KEYS = [
    'parent_id', 'department_id', 'group_id', 'role',
    'recursive_department_id', 'recursive_group_id', 'type',
    'admin_uid', 'member_uid',
];

function addChunkData(context, data) {
    if (!context.chunks) {
        context.chunks = {};
    }

    const filters = [];
    const query = data.query || {};

    FILTER_KEYS.forEach(key => {
        if (query[key] !== undefined) {
            filters.push(`${key}=${query[key]}`);
        }
    });

    const chunkKey = [data.type].concat(filters).join('/');
    const chunk = _.pick(data, ['type', 'pages', 'per_page', 'total', 'page']);

    chunk.size = (data.result || []).length;
    chunk.last = !data.pages || data.page === data.pages;
    chunk.items = (data.result || []).map(item => String(item.id));

    context.chunks[chunkKey] = chunk;
}

function stackResponse(context, key, data) {
    if (data === null || data === undefined) {
        return;
    }

    if (key === 'lists') {
        if (!context[key]) {
            context[key] = [];
        }
        addChunkData(context, data);
        context[key].push(data);
    } else if (typeof data === 'object' && data.id !== undefined) {
        if (!context[key]) {
            context[key] = {};
        }

        const id = String(data.id);

        context[key][id] = context[key][id] ? _.merge(context[key][id], data) : data;

        if (!context.sources) {
            context.sources = [];
        }

        context.sources.push({ id, type: ENTITY_TYPE_MAP[key] });
    }
}

module.exports = stackResponse;
