"use strict";
var argv = require('optimist')
    .usage('Extract details of all the quizzes from the MongoDB.\nUsage: $0')
    .demand('m')
    .alias('m', 'db-host')
    .describe('m', 'MongdoDB hostname and port')
    .alias('d', 'db')
    .default('d', 'quiz-renderer-test')
    .describe('d', 'name of database')
    .argv;



var mongoose = require('mongoose'),
    db = mongoose.connect(argv.m, argv.d);

db.connection.on('error', console.error.bind(console, 'connection error:'));

console.log('opened DB')

function onDBError(err, callback) {
    console.log("error! "+ err);
    mongoose.connection.close();
}


var q = {};
q.map = function() {
    x = this.questionAnswers.map(function(d,i) {
        if (d.correct)
            return 1;
        else
            return 0;
    } );
    emit (this.skillName,  {correctCounts:x});
};
q.verbose = true;
q.reduce = function(key, values) {
    return values.reduce(function(a, b) {
        a = a.correctCounts || [];
        b = b.correctCounts || [];
        var i = 0, j = 0, sum = [];
        for (; i < a.length; i++, j++) {
            var s = 0;
            if (i < b.length) {
                s = a[i] + b[j];
            }
            sum.push(s);
        }
        for (; j < b.length; j++) {
            sum.push(b[j]);
        }
        return {correctCounts: sum};
    });
};
q.query  = { };
q.out = { replace: 'createdCollectionNameForResults' }

var res = CodingQuestions.mapReduce(q, function(err, model, stats) {
    console.log('got results');
    console.log(err);
    model.find().exec(function (err, docs) {
        console.log("docs" + JSON.stringify(docs, null, 2) );
        mongoose.connection.close();
    });
});



console.log('ready.');
