 # 3.1 Determine with items have already been done enough
 getMaxedItems = (obj, callback) ->
   if obj.condition is 'teaching'
-    callback(obj, null)
+    callback(null, obj)
+  console.log "!!"+obj.opts.hit_id+"!!"
   # Get a list of all currentHIT items completed
-  TaskSet.aggregate({$match: {hit_id:hit_id}},
+  TaskSet#.find({hit_id:hit_id}
+    .aggregate({$match:{hit_id:obj.opts.hit_id}},
                   {$project:{"tasks.item.id":1}},
                   {$unwind : "$tasks"},
                   # Matching on task item id *after* unwinding


  switch obj.condition
    when 'feedback'
      '''TODO get user feedback and add to obj'''
      callback('Feedback condition not yet designed', obj)
    else
      callback(null, obj)

#
mongoose = require 'mongoose'
async = require 'async'
_ = require 'underscore'
#mongoose.connect 'mongodb://localhost/test'
#mongoose.connect 'mongodb://localhost/test'
#db = mongoose.connection

TaskSet = require './models/taskset'
Hit = require './models/hit'
ObjectId = mongoose.Types.ObjectId

loadHIT = (opts) ->
  #db.on('error', console.error.bind(console, 'connection error:'))

  #db.once('open', () ->
    async.waterfall([
      (cb) -> cb(null, opts) # Pipe opts to first func in waterfal
      getBasicInfo,
      getCondition,
      getMaxedItems,
      sampleTaskItems
    ], (err, results) ->
      if (err) then return console.error err
      console.log "Waterfall done"
      console.log results
    )
  #)

# 1. Count how many taskSets this user has done in this condition
# Also fetch HIT info, since it can be done asynchronously
getBasicInfo = (opts, callback) ->
  async.parallel({
    opts: (callback) -> callback(null, opts)
    # Count of all taskSets done by the user
    countUserAll: (callback) -> TaskSet.countUserAll(opts.user, callback)
    # Count of tasksets in the given condition done
    countUserHIT: (callback) -> TaskSet.countUserHIT(opts.user, opts.hit_id, callback)
    # List of user's past items completed (not specific to the current hit)
    userItemList: (callback) -> TaskSet.userItemList(opts.user, callback)
    # Load HIT info
    hit: (callback) -> Hit.findOne({_id: ObjectId(opts.hit_id)}, callback)
  },
  callback
  )

