/**
* Created by WORKER on 05-09-2015.
*/
var async = require("async");
var result = {};
var matches = [];
function done(err, doc) {
console.log(doc);
if (doc != null) {
//console.dir(doc);
matches.push(doc)
} else {
result._callback();
}
}
function getNames(result, options) {
var template = options.query.template;
switch (template) {
case 'whom':
console.log('Getting ' + template + ' names');
options.DB.NameClln.find({}, { _id: 1, name: 1 }).each(done);
break;
case 'checkin':
case 'checkout':
console.log('Getting ' + template + ' names');
options.DB.PlaceClln.find({}, { _id: 1, name: 1 }).each(done);
break;
default:
}
}
function matchNames(token, names) {
//var names = [{_id: 0, name: "Neha Sharma"}, {_id: 0, name: "Neha Arora"}, {_id: 0, name: "Neha Bhagwat"}, {_id: 0, name: "Neha Om Prakash"}, {_id: 0, name: "Neha Upreti"}];
var matches = [];
for (var name in names) {
var parts = names[name].name.split(" ");
for (var index in parts) {
var part = parts[index];
if(token.length <= part.length) {
var subpart = part.substring(0, token.length);
if (subpart.toLowerCase() === token.toLowerCase()) {
matches.push(names[name]);
break;
}
}
}
}
return matches;
}
/**
* Build list of person name matching a given token.
* @param {Object} options Input parameters
*/
function getNamelist(options) {
matches = [];
var data = {
list: []
}
var asyncTasks = [];
if(options.query.token && options.query.token.length > 0) {
asyncTasks.push(function (_callback) {
result._callback = _callback;
getNames(result, options);
});
asyncTasks.push(function (_callback) {
matches = matchNames(options.query.token, matches);
_callback();
});
}
async.series(asyncTasks, function(){
data.list = matches;
for (var match in data.list) {
console.log(data.list[match]);
}
options.res.json(data);
});
}
module.exports = getNamelist;