/* eslint no-param-reassign: "off" */

const _ = require('lodash');
const async = require('async');
const bovada = require('../services/bovada');
const DuelWeek = require('../models/DuelWeek');
const NFLWeek = require('../services/NFLWeek');

function updateGames(games, lines) {
  lines.forEach((line) => {
    const existingGame = games.find(game => line.id === game.id);
    if (existingGame === undefined) {
      games.push(line);
    } else if (!existingGame.selectedTeam && existingGame.startTime > +new Date()) {
      existingGame.homeSpread = line.homeSpread;
      existingGame.awaySpread = line.awaySpread;
    }
  });
  return games;
}

module.exports.call = (duels, cb) => {
  bovada.getLines((err, lines) => {
    if (err) { return cb(err); }
    const weekMap = _.groupBy(lines, NFLWeek.forGame);
    return async.each(duels, (duel, eachDuelCb) => {
      async.each(Object.keys(weekMap), (weekNum, eachWeekCb) => {
        DuelWeek.findOneAndUpdate(
          { year: NFLWeek.seasonYear, weekNum, duelId: duel.id },
          {
            betAmount: duel.betAmount,
            players: duel.players,
            picker: duel.players[weekNum % 2],
          },
          { upsert: true, setDefaultsOnInsert: true, runValidators: true, new: true },
          (findErr, duelWeek) => {
            if (findErr) { return eachWeekCb(findErr); }
            duelWeek.games = updateGames(duelWeek.games, weekMap[weekNum]);
            return duelWeek.save(eachWeekCb);
          }
        );
      }, eachDuelCb);
    }, cb);
  });
};

@@ -236,16 +236,117 @@
 eek');%0A%0A
+function unpickedAndNotBegun(game) %7B%0A  return !game.selectedTeam && game.startTime %3E +new Date();%0A%7D%0A%0A
 function
@@ -374,16 +374,16 @@
 ines) %7B%0A
-
   lines.
@@ -545,13 +545,16 @@
 lse 
-if (!
+%7B%0A      
 exis
@@ -567,58 +567,77 @@
 me.s
-electedTeam && existingGame.startTime %3E +new Date(
+tartTime = line.startTime;%0A      if (unpickedAndNotBegun(existingGame
 )) %7B
@@ -635,32 +635,34 @@
 gGame)) %7B%0A      
+ 
+ 
 existingGame.hom
@@ -690,24 +690,26 @@
 read;%0A      
+  
 existingGame
@@ -735,24 +735,32 @@
 awaySpread;%0A
+      %7D%0A
     %7D%0A  %7D);%0A

Update game start time regardless of picked status