const preprocessUser = require('../preprocessUser');
const preprocessService = require('../preprocessService');
const preprocessPagedList = require('../preprocessPagedList');
const record = require('../record');
const toObjectList = require('../toObjectList');

const SERVICE_ORDER = [
    'tracker', 'wiki',
    'metrika', 'direct', 'yandexsprav',
    'mail', 'disk', 'forms',
    'search', 'portal', 'staff', 'calendar', 'yamb', 'dashboard'
];

function preprocess(req, data, source) {
    if (!data) return {};
    if (data._preprocessed) return data;

    data.admin = preprocessUser(req, data.admin, data);
    data.safe_name = record.getSafeName(data);

    /*
    data.organization_type = 'partner_organization';
    data.subscription_plan_expires_at = '2018-12-21';
    */

    if (Array.isArray(data.admins)) {
        data.admins = toObjectList(req, data.admins, 'user', { org_id: data.id });
        data.owner = data.admins.find(item => item.object && String(item.object.id) === String(data.admin_uid));
    }

    if (data.services && !data.services.code) {
        let serviceKeys = SERVICE_ORDER.slice().concat(
            Object.keys(data.services || {})
                .filter(slug => SERVICE_ORDER.indexOf(slug) === -1)
        );

        data.services = serviceKeys.map(slug => {
            let service = data.services[slug] || { enabled: null };
            return preprocessService(req, Object.assign({ slug }, service));
        });
    }

    [ 'domains', 'tasks', 'actions', 'staff' ].forEach(key => {
        data[key] = preprocessPagedList(req, data[key]);
    });

    data._preprocessed = true;
    // console.log(JSON.stringify(data, null, 2));

    return data;
}

module.exports = preprocess;
