package info.nightscout.androidaps.queue.commands;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;

/**
 * Created by mike on 09.11.2017.
 */

public class CommandSMBBolus extends Command {
    private static Logger log = LoggerFactory.getLogger(CommandSMBBolus.class);
    DetailedBolusInfo detailedBolusInfo;

    public CommandSMBBolus(DetailedBolusInfo detailedBolusInfo, Callback callback) {
        commandType = CommandType.SMB_BOLUS;
        this.detailedBolusInfo = detailedBolusInfo;
        this.callback = callback;
    }

    @Override
    public void execute() {
        PumpEnactResult r;
        if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + 60 * 1000L > System.currentTimeMillis())
            r = ConfigBuilderPlugin.getActivePump().deliverTreatment(detailedBolusInfo);
        else {
            r = new PumpEnactResult().enacted(false).success(false).comment("SMB request too old");
            log.debug("SMB bolus canceled. delivetAt=" + detailedBolusInfo.deliverAt + " now=" + System.currentTimeMillis());
        }

        if (callback != null)
            callback.result(r).run();
    }

    public String status() {
        return "SMBBOLUS " + DecimalFormatter.to1Decimal(detailedBolusInfo.insulin) + "U";
    }
}

@@ -549,22 +549,132 @@
 aps.
-queue.Callback
+plugins.Treatments.TreatmentsPlugin;%0Aimport info.nightscout.androidaps.queue.Callback;%0Aimport info.nightscout.utils.DateUtil
 ;%0Aim
@@ -717,16 +717,48 @@
 rmatter;
+%0Aimport info.nightscout.utils.T;
 %0A%0A/**%0A *
@@ -1259,24 +1259,385 @@
  r;%0A        
+long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();%0A        if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() %3E DateUtil.now()) %7B%0A            log.debug(%22SMB requsted but still in 3 min interval%22);%0A            r = new PumpEnactResult().enacted(false).success(false).comment(%22SMB requsted but still in 3 min interval%22);%0A        %7D else 
 if (detailed
@@ -1698,18 +1698,25 @@
 t + 
-60 * 1000L
+T.mins(1).msecs()
  %3E S

check 3min timeout SMB right before execution