const _ = require('lodash');
const template = require('./common/template');

const GENDER_MAP = {
    '0': 'unspecified', '1': 'male', '2': 'female'
};

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

    data._preprocessed = true;

    if (data.login !== undefined) {
        data.nickname = data.nickname || data.login;
        delete data.login;
    }

    if (data.is_outer === undefined) {
        if (!data.id && source)
            data.id = source.admin_uid;

        data.birth_date = data.birthday;
        delete data.birthday;

        if (data.code !== 'not_found') {
            data.external = false;
        }
    }
    else {
        data.id = data.uid;
        delete data.uid;

        data.email = data.default_email;
        delete data.default_email;

        data.gender = GENDER_MAP[data.sex];
        delete data.sex;

        data.external = data.is_outer;
        delete data.is_outer;
    }

    data.avatar_url = template.build(_.get(req.context.config, 'ui.avatar'), {
        id: data.avatar_id || '0/0-0',
        size: 200
    });

    return data;
}

module.exports = preprocessUser;
