AndroidAPS/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt

309 lines
17 KiB
Kotlin
Raw Normal View History

2019-12-20 18:55:54 +01:00
package info.nightscout.androidaps.dialogs
2019-12-20 13:58:51 +01:00
2021-03-25 17:48:07 +01:00
import android.content.Context
2019-12-20 13:58:51 +01:00
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.common.base.Joiner
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
2021-03-25 17:48:07 +01:00
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo
2019-12-20 13:58:51 +01:00
import info.nightscout.androidaps.data.Profile
2021-03-01 12:42:42 +01:00
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryTarget
2021-03-25 17:48:07 +01:00
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Units
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
2021-03-01 12:42:42 +01:00
import info.nightscout.androidaps.database.transactions.InsertTemporaryTargetAndCancelCurrentTransaction
2021-01-21 17:03:05 +01:00
import info.nightscout.androidaps.databinding.DialogCarbsBinding
2019-12-20 13:58:51 +01:00
import info.nightscout.androidaps.interfaces.Constraint
2020-05-07 09:54:36 +02:00
import info.nightscout.androidaps.interfaces.ProfileFunction
2021-03-01 12:42:42 +01:00
import info.nightscout.androidaps.logging.LTag
2021-02-09 17:57:28 +01:00
import info.nightscout.androidaps.logging.UserEntryLogger
2020-08-19 21:24:01 +02:00
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
2020-01-10 23:14:58 +01:00
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
2019-12-20 13:58:51 +01:00
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
2021-03-25 17:48:07 +01:00
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.CommandQueue
2021-02-13 21:45:14 +01:00
import info.nightscout.androidaps.utils.*
2020-04-08 14:03:57 +02:00
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
2020-08-19 21:24:01 +02:00
import info.nightscout.androidaps.utils.extensions.formatColor
2019-12-27 19:20:38 +01:00
import info.nightscout.androidaps.utils.resources.ResourceHelper
2021-03-01 12:42:42 +01:00
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
2019-12-20 13:58:51 +01:00
import java.text.DecimalFormat
import java.util.*
2021-03-01 12:42:42 +01:00
import java.util.concurrent.TimeUnit
2019-12-27 19:20:38 +01:00
import javax.inject.Inject
2019-12-20 13:58:51 +01:00
import kotlin.math.max
class CarbsDialog : DialogFragmentWithDate() {
2021-01-21 17:03:05 +01:00
2021-03-25 17:48:07 +01:00
@Inject lateinit var ctx: Context
2019-12-30 00:53:44 +01:00
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker
2020-01-01 23:23:16 +01:00
@Inject lateinit var defaultValueHelper: DefaultValueHelper
2019-12-30 00:53:44 +01:00
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
2019-12-31 00:37:36 +01:00
@Inject lateinit var profileFunction: ProfileFunction
2020-02-28 18:20:31 +01:00
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
2021-02-09 17:57:28 +01:00
@Inject lateinit var uel: UserEntryLogger
2021-02-13 21:45:14 +01:00
@Inject lateinit var carbTimer: CarbTimer
2021-03-25 17:48:07 +01:00
@Inject lateinit var commandQueue: CommandQueue
2021-03-01 12:42:42 +01:00
@Inject lateinit var repository: AppRepository
2019-12-27 19:20:38 +01:00
2019-12-20 13:58:51 +01:00
companion object {
2021-01-21 17:03:05 +01:00
2019-12-20 13:58:51 +01:00
private const val FAV1_DEFAULT = 5
private const val FAV2_DEFAULT = 10
private const val FAV3_DEFAULT = 20
}
2021-03-01 12:42:42 +01:00
private val disposable = CompositeDisposable()
2019-12-20 13:58:51 +01:00
private val textWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {
validateInputs()
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
}
private fun validateInputs() {
2019-12-27 19:20:38 +01:00
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
2021-01-21 17:03:05 +01:00
val time = binding.time.value.toInt()
2019-12-20 13:58:51 +01:00
if (time > 12 * 60 || time < -12 * 60) {
2021-01-21 17:03:05 +01:00
binding.time.value = 0.0
2021-03-25 17:48:07 +01:00
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied))
2019-12-20 13:58:51 +01:00
}
2021-01-21 17:03:05 +01:00
if (binding.duration.value > 10) {
binding.duration.value = 0.0
2021-03-25 17:48:07 +01:00
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied))
2019-12-20 13:58:51 +01:00
}
2021-01-21 17:03:05 +01:00
if (binding.carbs.value.toInt() > maxCarbs) {
binding.carbs.value = 0.0
2021-03-25 17:48:07 +01:00
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.carbsconstraintapplied))
2019-12-20 13:58:51 +01:00
}
}
2021-01-21 17:03:05 +01:00
private var _binding: DialogCarbsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
2019-12-20 13:58:51 +01:00
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
2021-01-21 17:03:05 +01:00
savedInstanceState.putDouble("time", binding.time.value)
savedInstanceState.putDouble("duration", binding.duration.value)
savedInstanceState.putDouble("carbs", binding.carbs.value)
2019-12-20 13:58:51 +01:00
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
2021-01-21 17:03:05 +01:00
savedInstanceState: Bundle?): View {
2019-12-20 23:05:35 +01:00
onCreateViewGeneral()
2021-01-21 17:03:05 +01:00
_binding = DialogCarbsBinding.inflate(inflater, container, false)
return binding.root
2019-12-20 13:58:51 +01:00
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
2019-12-27 19:20:38 +01:00
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
2021-01-21 17:03:05 +01:00
binding.time.setParams(savedInstanceState?.getDouble("time")
?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher)
2019-12-20 13:58:51 +01:00
2021-01-21 17:03:05 +01:00
binding.duration.setParams(savedInstanceState?.getDouble("duration")
?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher)
2019-12-20 13:58:51 +01:00
2021-01-21 17:03:05 +01:00
binding.carbs.setParams(savedInstanceState?.getDouble("carbs")
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher)
2019-12-20 13:58:51 +01:00
2021-01-21 17:03:05 +01:00
binding.plus1.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
binding.plus1.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value
2019-12-30 00:53:44 +01:00
+ sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
2019-12-20 13:58:51 +01:00
validateInputs()
}
2021-01-21 17:03:05 +01:00
binding.plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
binding.plus2.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value
2019-12-30 00:53:44 +01:00
+ sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
2019-12-20 13:58:51 +01:00
validateInputs()
}
2021-01-21 17:03:05 +01:00
binding.plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
binding.plus3.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value
2019-12-30 00:53:44 +01:00
+ sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
2019-12-20 13:58:51 +01:00
validateInputs()
}
2020-01-10 23:14:58 +01:00
iobCobCalculatorPlugin.actualBg()?.let { bgReading ->
2019-12-20 13:58:51 +01:00
if (bgReading.value < 72)
2021-01-21 17:03:05 +01:00
binding.hypoTt.isChecked = true
2019-12-20 13:58:51 +01:00
}
2021-01-21 17:03:05 +01:00
binding.hypoTt.setOnClickListener {
binding.activityTt.isChecked = false
binding.eatingSoonTt.isChecked = false
2019-12-20 13:58:51 +01:00
}
2021-01-21 17:03:05 +01:00
binding.activityTt.setOnClickListener {
binding.hypoTt.isChecked = false
binding.eatingSoonTt.isChecked = false
2019-12-20 13:58:51 +01:00
}
2021-01-21 17:03:05 +01:00
binding.eatingSoonTt.setOnClickListener {
binding.hypoTt.isChecked = false
binding.activityTt.isChecked = false
2019-12-20 13:58:51 +01:00
}
}
2021-01-21 17:03:05 +01:00
override fun onDestroyView() {
super.onDestroyView()
2021-03-01 12:42:42 +01:00
disposable.clear()
2021-01-21 17:03:05 +01:00
_binding = null
}
2019-12-20 13:58:51 +01:00
private fun toSignedString(value: Int): String {
return if (value > 0) "+$value" else value.toString()
}
2019-12-21 23:17:20 +01:00
override fun submit(): Boolean {
2021-01-21 17:03:05 +01:00
if (_binding == null) return false
val carbs = binding.carbs.value?.toInt() ?: return false
2019-12-27 19:20:38 +01:00
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
2019-12-31 00:37:36 +01:00
val units = profileFunction.getUnits()
2020-01-01 23:23:16 +01:00
val activityTTDuration = defaultValueHelper.determineActivityTTDuration()
val activityTT = defaultValueHelper.determineActivityTT()
val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration()
val eatingSoonTT = defaultValueHelper.determineEatingSoonTT()
val hypoTTDuration = defaultValueHelper.determineHypoTTDuration()
val hypoTT = defaultValueHelper.determineHypoTT()
2019-12-20 13:58:51 +01:00
val actions: LinkedList<String?> = LinkedList()
2019-12-27 19:20:38 +01:00
val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl)
2021-02-13 21:45:14 +01:00
val useAlarm = binding.alarmCheckBox.isChecked
2019-12-20 13:58:51 +01:00
2021-01-21 17:03:05 +01:00
val activitySelected = binding.activityTt.isChecked
2019-12-20 13:58:51 +01:00
if (activitySelected)
2020-08-19 21:24:01 +02:00
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation))
2021-01-21 17:03:05 +01:00
val eatingSoonSelected = binding.eatingSoonTt.isChecked
2019-12-20 13:58:51 +01:00
if (eatingSoonSelected)
2020-08-19 21:24:01 +02:00
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation))
2021-01-21 17:03:05 +01:00
val hypoSelected = binding.hypoTt.isChecked
2019-12-20 13:58:51 +01:00
if (hypoSelected)
2020-08-19 21:24:01 +02:00
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation))
2019-12-20 13:58:51 +01:00
2021-01-21 17:03:05 +01:00
val timeOffset = binding.time.value.toInt()
eventTime -= eventTime % 1000
2020-01-02 00:40:03 +01:00
val time = eventTime + timeOffset * 1000 * 60
2019-12-20 13:58:51 +01:00
if (timeOffset != 0)
2020-05-07 23:40:59 +02:00
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
2021-02-13 21:45:14 +01:00
if (useAlarm && carbs > 0 && timeOffset > 0)
actions.add(resourceHelper.gs(R.string.alarminxmin, timeOffset).formatColor(resourceHelper, R.color.info))
2021-01-21 17:03:05 +01:00
val duration = binding.duration.value.toInt()
2019-12-20 13:58:51 +01:00
if (duration > 0)
2019-12-27 19:20:38 +01:00
actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour))
2019-12-20 15:36:27 +01:00
if (carbsAfterConstraints > 0) {
2019-12-27 19:20:38 +01:00
actions.add(resourceHelper.gs(R.string.carbs) + ": " + "<font color='" + resourceHelper.gc(R.color.carbs) + "'>" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>")
2019-12-20 15:36:27 +01:00
if (carbsAfterConstraints != carbs)
2019-12-27 19:20:38 +01:00
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.carbsconstraintapplied) + "</font>")
2019-12-20 15:36:27 +01:00
}
2021-01-21 17:03:05 +01:00
val notes = binding.notesLayout.notes.text.toString()
2019-12-20 13:58:51 +01:00
if (notes.isNotEmpty())
2021-02-22 18:04:30 +01:00
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes)
2019-12-20 13:58:51 +01:00
2020-01-02 00:40:03 +01:00
if (eventTimeChanged)
2020-05-07 23:40:59 +02:00
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
2020-01-02 00:40:03 +01:00
2019-12-20 13:58:51 +01:00
if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) {
activity?.let { activity ->
2021-01-21 17:03:05 +01:00
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
2019-12-30 00:53:44 +01:00
when {
activitySelected -> {
2021-03-22 16:59:09 +01:00
uel.log(Action.TT, ValueWithUnit(TemporaryTarget.Reason.ACTIVITY.text, Units.TherapyEvent), ValueWithUnit(activityTT, units), ValueWithUnit(activityTTDuration, Units.M))
2021-03-01 12:42:42 +01:00
disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction(
timestamp = System.currentTimeMillis(),
duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()),
reason = TemporaryTarget.Reason.ACTIVITY,
lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()),
highTarget = Profile.toMgdl(activityTT, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
2021-03-01 12:42:42 +01:00
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
2021-03-01 12:42:42 +01:00
})
2019-12-30 00:53:44 +01:00
}
eatingSoonSelected -> {
2021-03-22 16:59:09 +01:00
uel.log(Action.TT, ValueWithUnit(TemporaryTarget.Reason.EATING_SOON.text, Units.TherapyEvent), ValueWithUnit(eatingSoonTT, units), ValueWithUnit(eatingSoonTTDuration, Units.M))
2021-03-01 12:42:42 +01:00
disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction(
timestamp = System.currentTimeMillis(),
duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()),
reason = TemporaryTarget.Reason.EATING_SOON,
lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()),
highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
2021-03-01 12:42:42 +01:00
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
2021-03-01 12:42:42 +01:00
})
2019-12-30 00:53:44 +01:00
}
hypoSelected -> {
2021-03-22 16:59:09 +01:00
uel.log(Action.TT, ValueWithUnit(TemporaryTarget.Reason.HYPOGLYCEMIA.text, Units.TherapyEvent), ValueWithUnit(hypoTT, units), ValueWithUnit(hypoTTDuration, Units.M))
2021-03-01 12:42:42 +01:00
disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction(
timestamp = System.currentTimeMillis(),
duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()),
reason = TemporaryTarget.Reason.HYPOGLYCEMIA,
lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()),
highTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
2021-03-01 12:42:42 +01:00
}, {
2021-03-25 23:52:08 +01:00
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
2021-03-01 12:42:42 +01:00
})
2019-12-30 00:53:44 +01:00
}
2019-12-20 13:58:51 +01:00
}
if (carbsAfterConstraints > 0) {
2021-03-25 17:48:07 +01:00
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.eventType = DetailedBolusInfo.EventType.CORRECTION_BOLUS
detailedBolusInfo.carbs = carbsAfterConstraints.toDouble()
detailedBolusInfo.context = context
detailedBolusInfo.notes = notes
detailedBolusInfo.carbsDuration = T.mins(duration.toLong()).msecs()
2021-03-25 23:52:08 +01:00
detailedBolusInfo.carbsTimestamp = time
uel.log(Action.CARBS, detailedBolusInfo.notes,
ValueWithUnit(detailedBolusInfo.timestamp, Units.Timestamp),
ValueWithUnit(detailedBolusInfo.carbs, Units.G),
ValueWithUnit(detailedBolusInfo.carbTime, Units.M, detailedBolusInfo.carbTime != 0),
ValueWithUnit(detailedBolusInfo.carbsDuration, Units.H, detailedBolusInfo.carbsDuration != 0L)
)
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} else
uel.log(Action.BOLUS, notes, ValueWithUnit(carbsAfterConstraints, Units.G))
2021-03-25 17:48:07 +01:00
2021-03-25 23:52:08 +01:00
}
})
2019-12-20 13:58:51 +01:00
}
2021-02-13 21:45:14 +01:00
if (useAlarm && carbs > 0 && timeOffset > 0) {
carbTimer.scheduleReminder(dateUtil._now() + T.mins(timeOffset.toLong()).msecs())
}
2019-12-22 21:37:26 +01:00
}, null)
2019-12-20 13:58:51 +01:00
}
} else
2019-12-22 21:37:26 +01:00
activity?.let { activity ->
2019-12-27 19:20:38 +01:00
OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected))
2019-12-22 21:37:26 +01:00
}
2019-12-21 23:17:20 +01:00
return true
2019-12-20 13:58:51 +01:00
}
}