var _ = require('lodash');
var i18n = require('../common/i18n');

const FALLBACK_LOCALE = 'ru';

function localized_value(object, key, options) {
    if (!object || typeof object !== 'object') {
        return '';
    }

    var keys = [
        key + '.' + i18n.getLocale(options),
        key + '.' + FALLBACK_LOCALE,
        key
    ];

    for (let i = 0; i < keys.length; i++) {
        let value = _.get(object, keys[i]);
        if (value !== undefined) {
            return value;
        }
    }
}

function user_name(object, options) {
    if (!object || typeof object !== 'object') {
        return '';
    }
    return [
        object.first_name || localized_value(object, 'name.first', options),
        object.last_name || localized_value(object, 'name.last', options)
    ].filter(Boolean).join(' ');
}

function object_name(object, options) {
    if (!object || typeof object !== 'object') {
        return '';
    }
    return object.nickname === undefined ? localized_value(object, 'name', options) : user_name(object, options);
}

function object_description(object, options) {
    if (!object || typeof object !== 'object') {
        return '';
    }
    if (object.description_plain !== undefined) {
        return object.description_plain;
    }
    if (object.description !== undefined) {
        return localized_value(object, 'description', options);
    }
    if (object.position_plain !== undefined) {
        return object.position_plain;
    }
    if (object.position !== undefined) {
        return localized_value(object, 'position', options);
    }
}

function object_contents(object, options) {
    if (!object || typeof object !== 'object') {
        return '';
    }
    if (typeof object.members_count === 'number') {
        let dictionary = i18n.getDictionary(options);
        return dictionary.pluralize(object.members_count, dictionary.pick('common.employees'));
    }
}

function object_aliases(object, options) {
    if (!object || !object.aliases || !object.aliases.length) {
        return '';
    }

    var key = object.aliases.length === 1 ? 'single' : 'multiple';
    var dictionary = i18n.getDictionary(options);

    return `${dictionary.pick('user_details.aliases.' + key)}: ${object.aliases.join(', ')}`;
}

module.exports = {
    localized_value,
    user_name,
    object_name,
    object_description,
    object_contents,
    object_aliases
};
