/**
 * Connect to mongo data base.
 * @function lib.db._connectMongo
 * @param {string} url - Data base url.
 * @param {object} models - Model array.
 * @protected
 * @ignore
 * @author Taka Okunishi
 *
 */
var string = require('../../lib/string'),
    pluralize = string.pluralize,
    underscorize = string.underscorize;

exports = module.exports = function (url, models) {
    if (!models) models = {};
    Object.keys(models)
        .forEach(function (key) {
            var model = models[key];
            model.prototype._mongoDocumentName = exports._nameDocument(key);
        });

    var documentNames = Object.keys(models).map(function (key) {
        var model = models[key];
        return model.prototype._mongoDocumentName;
    });

    var connection = require('mongojs').connect(url, documentNames);

    Object.keys(models).map(function (key) {
        var model = models[key];
        var documentName = model.prototype._mongoDocumentName;
        model.prototype._connection = connection[documentName];
    });

    return  connection;
};

exports._nameDocument = function (key) {
    return pluralize(underscorize(key));
};