
var getTime = require('../medtronic-clock');

function bgTargetsLookup (inputs) {
  return bound_target_range(lookup(inputs));
}

function lookup (inputs) {
    var bgtargets_data = inputs.targets;
    var now = new Date();
    
    //bgtargets_data.targets.sort(function (a, b) { return a.offset > b.offset });

    var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1]
    
    for (var i = 0; i < bgtargets_data.targets.length - 1; i++) {
        if ((now >= getTime(bgtargets_data.targets[i].offset)) && (now < getTime(bgtargets_data.targets[i + 1].offset))) {
            bgTargets = bgtargets_data.targets[i];
            break;
        }
    }

    return bgTargets;
}

function bound_target_range (target) {
    // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong
    target.max_bg = Math.max(90, target.high);
    target.min_bg = Math.max(90, target.low);
    // hard-code upper bound for min_bg in case pump is set too high
    target.min_bg = Math.min(200, target.min_bg);
    return target
}

bgTargetsLookup.bgTargetsLookup = bgTargetsLookup;
bgTargetsLookup.lookup = lookup;
bgTargetsLookup.bound_target_range = bound_target_range;
exports = module.exports = bgTargetsLookup;


@@ -192,16 +192,63 @@
 argets;%0A
+    var temptargets_data = inputs.temptargets;%0A
     var 
@@ -265,16 +265,16 @@
 Date();%0A
-
     %0A   
@@ -431,16 +431,17 @@
 gth - 1%5D
+;
 %0A    %0A  
@@ -714,16 +714,654 @@
 %0A    %7D%0A%0A
+    console.error(temptargets_data);%0A    console.log(now);%0A    for (var i = 0; i %3C temptargets_data.length; i++) %7B%0A        start = new Date(temptargets_data%5Bi%5D.created_at);%0A        console.log(start);%0A        expires = new Date(start.getTime() + temptargets_data%5Bi%5D.duration * 60 * 1000);%0A        console.log(expires);%0A        if (now %3E= new Date(temptargets_data%5Bi%5D.created_at) && now %3C expires ) %7B%0A            console.error(temptargets_data%5Bi%5D);%0A            bgTargets.high = temptargets_data%5Bi%5D.targetTop;%0A            bgTargets.low = temptargets_data%5Bi%5D.targetBottom;%0A            //break;%0A        %7D%0A    %7D%0A    console.error(bgTargets);%0A%0A
     retu
@@ -1537,33 +1537,33 @@
 x_bg = Math.max(
-9
+8
 0, target.high);
@@ -1596,9 +1596,9 @@
 max(
-9
+8
 0, t

allow temptargets to override bgTargets, down to 80