'use strict';
var async = require('async');
var _ = require('lodash');

/**
 * Webhook handler to award badges based on courses
 * Courses "Code" must correspond to the badge slug
 * @param  {Object} certificate contains all the info, header/user/course passed
 */
function awardLMSBadge (args, cb) {
  var seneca = this;
  var plugin = args.role;
  var certif = args;
  var user = certif.user;

  function checkTestStatus (waterfallCb) {
    if (certif.header.webHookType !== 'course_completion')
      return cb(null, 'Unhandled webhook');
    if (certif.enrollmentStatus !== 'passed' && certif.enrollmentStatus !== 'completed' )
      return cb(null, 'Unhandled status');
    waterfallCb(null, certif.courseReferenceCode);
  }

  function getBadge (badgeName, waterfallCb) {
    seneca.act({role: 'cd-badges', cmd: 'getBadge', slug: badgeName},
      function (err, badge) {
        if (err) return cb(err);
        waterfallCb(null, badge);
    });
  }

  function getUser (badge, waterfallCb) {
    seneca.act({role: 'cd-users', cmd: 'list', query: {lmsId: user.userId}},
      function (err, sysUser) {
        if (err) return cb(err);
        if (_.isEmpty(sysUser)) return cb(null, {ok: false, why: 'LMSUser not found'});
        return waterfallCb(null, sysUser[0], badge);
    });
  }

  function awardBadge (sysUser, badge, waterfallCb) {
    var applicationData = {
      user: sysUser,
      badge: badge.badge,
      emailSubject: 'You have been awarded a new CoderDojo digital badge!'
    };
    seneca.act({role: 'cd-badges', cmd: 'sendBadgeApplication',
        applicationData: applicationData,
        user: {id: null}
      },
      function (err, user) {
        if (err) return cb(err);
        waterfallCb();
    });
  }


  async.waterfall([
    checkTestStatus,
    getBadge,
    getUser,
    awardBadge
  ], cb);

}

module.exports = awardLMSBadge;

@@ -254,16 +254,1031 @@
  passed%0A
+ * ie: %7B%22header%22:%7B%22source%22:%22LearnUpon%22,%22version%22:1,%22webhookId%22:2213843,%22attempt%22:2,%22lastAttemptAt%22:%222016-09-01T10:33:32Z%22,%22webHookType%22:%22course_completion%22,%22signature%22:%225736605a1627415455de6f7ca50e7e9d%22%7D,%22user%22:%7B%22userId%22:12345,%22lastName%22:null,%22firstName%22:null,%22email%22:%22qq@example.com%22,%22username%22:null,%22customData%22:null%7D,%22enrollmentId%22:42,%22courseId%22:42,%22courseName%22:%22CoderDojo Ethos: Implementation and Practice%22,%22courseReferenceCode%22:%22coderdojo-ethos:-implementation-and-practice%22,%22courseMetaData%22:null,%22modules%22:%5B%7B%22id%22:42,%22type%22:%22scorm%22,%22name%22:%22CoderDojo Ethos: Implementation and Practice%22,%22status%22:%22passed%22,%22percentage%22:100.0,%22dateCompleted%22:null,%22attempts%22:null,%22isKnowledgeCheck%22:false%7D%5D,%22credits%22:%5B%5D,%22courseAccessExpiresAt%22:null,%22certification%22:false,%22certificationName%22:null,%22certExpiresAt%22:null,%22wasRecertified%22:false,%22dateEnrolled%22:%222016-08-29T12:02:38Z%22,%22dateStarted%22:%222016-09-01T10:30:50Z%22,%22dateCompleted%22:%222016-09-01T10:32:28Z%22,%22percentage%22:100,%22enrollmentStatus%22:%22passed%22,%22hasAttemptsRemaining%22:false%7D%0A
  */%0Afunc
@@ -1505,16 +1505,18 @@
 letion')
+ %7B
 %0A      r
@@ -1521,32 +1521,49 @@
  return cb(null,
+ %7Bok: false, why:
  'Unhandled webh
@@ -1570,46 +1570,61 @@
 ook'
+%7D
 );%0A    
-if (certif.enrollmentS
+%7D%0A    if (!_.every(certif.modules, %7B's
 tatus
- !==
+':
  'pa
@@ -1632,53 +1632,144 @@
 sed'
+%7D)
  &&
- certif.enrollmentStatus !== 'completed' )
+%0A      !_.every(certif.modules, %7B'status': 'completed'%7D) &&%0A      !_.includes(%5B'completed', 'passed'%5D, certif.enrollmentStatus) ) %7B
 %0A   
@@ -1786,16 +1786,33 @@
 cb(null,
+ %7Bok: false, why:
  'Unhand
@@ -1822,19 +1822,26 @@
  status'
+%7D
 );%0A
+    %7D%0A
     wate

Add enrollment check based upon modules status instead of only the global status