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

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

const BOT_USER_TYPES = [ 'robot', 'yamb_bot' ];

function toObjectList(req, data, commonType, context = {}) {
    if (!data) return [];

    data = data.map(item => {
        let object = item.object ? item.object : item;
        let type = item.object ? (item.object_type || item.type) : commonType;

        if (type === 'user')
            object = preprocessUser(req, object);

        let updatedItem = { object, type };

        if (object) {
            updatedItem.url = `/organizations/${object.org_id || context.org_id}/${SECTION_MAP[type]}/${object.id}`;
            updatedItem.removed = Boolean(object.removed || object.is_dismissed);
            updatedItem.bot = BOT_USER_TYPES.indexOf(object.user_type) !== -1;

            switch (type) {
                case 'user':
                    if (BOT_USER_TYPES.indexOf(object.user_type) !== -1)
                        updatedItem.visibility = 'hidden.bot';
                    if (object.external)
                        updatedItem.visibility = 'hidden.external_admin';
                    break;
                case 'group':
                    if (object.type !== 'generic')
                        updatedItem.visibility = 'hidden.technical_group';
                    break;
            }

            if (!updatedItem.visibility)
                updatedItem.visibility = 'normal';
        }

        return updatedItem;
    });

    return data;
}

module.exports = toObjectList;
