<commit_before>package info.nightscout.androidaps.dialogs

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.FragmentManager
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.dialog_loop.*
import javax.inject.Inject

class LoopDialog : DaggerDialogFragment() {

    @Inject lateinit var aapsLogger: AAPSLogger
    @Inject lateinit var mainApp: MainApp
    @Inject lateinit var sp: SP
    @Inject lateinit var rxBus: RxBusWrapper
    @Inject lateinit var fabricPrivacy: FabricPrivacy
    @Inject lateinit var resourceHelper: ResourceHelper
    @Inject lateinit var profileFunction: ProfileFunction
    @Inject lateinit var loopPlugin: LoopPlugin
    @Inject lateinit var objectivesPlugin: ObjectivesPlugin
    @Inject lateinit var activePlugin: ActivePluginProvider
    @Inject lateinit var constraintChecker: ConstraintChecker
    @Inject lateinit var commandQueue: CommandQueueProvider
    @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin

    private var disposable: CompositeDisposable = CompositeDisposable()

    private var showOkCancel: Boolean = true

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        savedInstanceState.putInt("showOkCancel", if (showOkCancel) 1 else 0)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // load data from bundle
        (savedInstanceState ?: arguments)?.let { bundle ->
            showOkCancel = bundle.getInt("showOkCancel", 1) == 1
        }
        dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
        dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        isCancelable = true
        dialog?.setCanceledOnTouchOutside(false)

        return inflater.inflate(R.layout.dialog_loop, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        updateGUI("LoopDialogOnViewCreated")

        overview_closeloop?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_lgsloop?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_openloop?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disable?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_enable?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_resume?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_reconnect?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_suspend_1h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_suspend_2h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_suspend_3h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_suspend_10h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disconnect_15m?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disconnect_30m?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disconnect_1h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disconnect_2h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        overview_disconnect_3h?.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }

        // cancel button
        cancel?.setOnClickListener { dismiss() }

        // bus
        disposable.add(rxBus
            .toObservable(EventNewOpenLoopNotification::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                activity?.runOnUiThread { updateGUI("EventNewOpenLoopNotification") }
            }, { fabricPrivacy.logException(it) })
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        disposable.clear()
    }

    fun updateGUI(from: String) {
        aapsLogger.debug("UpdateGUI from $from")
        val pumpDescription: PumpDescription = activePlugin.activePump.pumpDescription
        val closedLoopAllowed = objectivesPlugin.isClosedLoopAllowed(Constraint(true))
        val lgsEnabled = objectivesPlugin.isLgsAllowed(Constraint(true))
        var APSmode = sp.getString(R.string.key_aps_mode, "open")
        if (profileFunction.isProfileValid("LoopDialogUpdateGUI")) {
            if (loopPlugin.isEnabled(PluginType.LOOP)) {
                if (closedLoopAllowed.value()) {
                    overview_closeloop?.visibility = if (APSmode == "closed") View.GONE else View.VISIBLE
                    overview_lgsloop?.visibility = if (APSmode == "lgs") View.GONE else View.VISIBLE
                    overview_openloop?.visibility = if (APSmode == "open") View.GONE else View.VISIBLE
                } else if (lgsEnabled.value() ) {
                    overview_closeloop?.visibility = View.GONE
                    overview_lgsloop?.visibility = if (APSmode == "lgs") View.GONE else View.VISIBLE
                    overview_openloop?.visibility = if (APSmode == "open") View.GONE else View.VISIBLE
                } else {
                    overview_closeloop?.visibility = View.GONE
                    overview_lgsloop?.visibility = View.GONE
                    overview_openloop?.visibility = View.GONE
                }
                overview_enable?.visibility = View.GONE          //sp.getBoolean(R.string.key_usesuperbolus, false).toVisibility()
                overview_disable?.visibility = View.VISIBLE
               if (!loopPlugin.isSuspended) {
                    overview_suspend_header?.text=resourceHelper.gs(R.string.suspendloop)
                    overview_resume?.visibility = View.GONE
                    overview_suspend_buttons?.visibility=View.VISIBLE
                    overview_suspend?.visibility=View.VISIBLE
                } else {
                    if (!loopPlugin.isDisconnected) {
                        overview_suspend_header?.text = resourceHelper.gs(R.string.resumeloop)
                        overview_resume?.visibility = View.VISIBLE
                        overview_suspend_buttons?.visibility=View.GONE
                        overview_suspend?.visibility=View.VISIBLE
                    } else
                        overview_suspend?.visibility = View.GONE
                }
            } else {
                overview_enable?.visibility = View.VISIBLE
                overview_disable?.visibility = View.GONE
                overview_suspend?.visibility = View.GONE
            }
            if (!loopPlugin.isDisconnected) {
                overview_pump_header?.text = resourceHelper.gs(R.string.disconnectpump)
                overview_disconnect_15m?.visibility = if (pumpDescription.tempDurationStep15mAllowed) View.VISIBLE else View.GONE
                overview_disconnect_15m?.visibility = if (pumpDescription.tempDurationStep30mAllowed) View.VISIBLE else View.GONE
                overview_disconnect_buttons?.visibility = View.VISIBLE
                overview_reconnect?.visibility = View.GONE
            } else {
                overview_pump_header?.text = resourceHelper.gs(R.string.reconnect)
                overview_disconnect_buttons?.visibility = View.GONE
                overview_reconnect?.visibility = View.VISIBLE
            }
        }
        val profile = profileFunction.getProfile()
        val profileStore = activePlugin.activeProfileInterface.profile

        if (profile == null || profileStore == null) {
            ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile))
            dismiss()
            return
        }

    }

    fun onClick_OkCancelEnabled(v: View): Boolean {
        var description = ""
        when(v.id) {
            R.id.overview_closeloop         -> description = resourceHelper.gs(R.string.closedloop)
            R.id.overview_lgsloop           -> description = resourceHelper.gs(R.string.lowglucosesuspend)
            R.id.overview_openloop          -> description = resourceHelper.gs(R.string.openloop)
            R.id.overview_disable           -> description = resourceHelper.gs(R.string.disableloop)
            R.id.overview_enable            -> description = resourceHelper.gs(R.string.enableloop)<commit_msg>Use Jetpack instead of Kotlin<commit_after>package info.nightscout.androidaps.dialogs

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.FragmentManager
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.databinding.DialogLoopBinding
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject

class LoopDialog : DaggerDialogFragment() {

    @Inject lateinit var aapsLogger: AAPSLogger
    @Inject lateinit var mainApp: MainApp
    @Inject lateinit var sp: SP
    @Inject lateinit var rxBus: RxBusWrapper
    @Inject lateinit var fabricPrivacy: FabricPrivacy
    @Inject lateinit var resourceHelper: ResourceHelper
    @Inject lateinit var profileFunction: ProfileFunction
    @Inject lateinit var loopPlugin: LoopPlugin
    @Inject lateinit var objectivesPlugin: ObjectivesPlugin
    @Inject lateinit var activePlugin: ActivePluginProvider
    @Inject lateinit var constraintChecker: ConstraintChecker
    @Inject lateinit var commandQueue: CommandQueueProvider
    @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin

    private var disposable: CompositeDisposable = CompositeDisposable()

    private var showOkCancel: Boolean = true
    private var _binding: DialogLoopBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        savedInstanceState.putInt("showOkCancel", if (showOkCancel) 1 else 0)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // load data from bundle
        (savedInstanceState ?: arguments)?.let { bundle ->
            showOkCancel = bundle.getInt("showOkCancel", 1) == 1
        }
        dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
        dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        isCancelable = true
        dialog?.setCanceledOnTouchOutside(false)

        _binding = DialogLoopBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        updateGUI("LoopDialogOnViewCreated")

        binding.overviewCloseloop.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewLgsloop.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewOpenloop.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisable.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewEnable.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewResume.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewReconnect.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewSuspend1h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewSuspend2h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewSuspend3h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewSuspend10h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisconnect15m.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisconnect30m.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisconnect1h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisconnect2h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }
        binding.overviewDisconnect3h.setOnClickListener { if(showOkCancel) onClick_OkCancelEnabled(it) else onClick(it); dismiss() }

        // cancel button
        binding.cancel.setOnClickListener { dismiss() }

        // bus
        disposable.add(rxBus
            .toObservable(EventNewOpenLoopNotification::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                activity?.runOnUiThread { updateGUI("EventNewOpenLoopNotification") }
            }, { fabricPrivacy.logException(it) })
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        disposable.clear()
    }

    fun updateGUI(from: String) {
        aapsLogger.debug("UpdateGUI from $from")
        val pumpDescription: PumpDescription = activePlugin.activePump.pumpDescription
        val closedLoopAllowed = objectivesPlugin.isClosedLoopAllowed(Constraint(true))
        val lgsEnabled = objectivesPlugin.isLgsAllowed(Constraint(true))
        var APSmode = sp.getString(R.string.key_aps_mode, "open")
        if (profileFunction.isProfileValid("LoopDialogUpdateGUI")) {
            if (loopPlugin.isEnabled(PluginType.LOOP)) {
                if (closedLoopAllowed.value()) {
                    binding.overviewCloseloop.visibility = if (APSmode == "closed") View.GONE else View.VISIBLE
                    binding.overviewLgsloop.visibility = if (APSmode == "lgs") View.GONE else View.VISIBLE
                    binding.overviewOpenloop.visibility = if (APSmode == "open") View.GONE else View.VISIBLE
                } else if (lgsEnabled.value() ) {
                    binding.overviewCloseloop.visibility = View.GONE
                    binding.overviewLgsloop.visibility = if (APSmode == "lgs") View.GONE else View.VISIBLE
                    binding.overviewOpenloop.visibility = if (APSmode == "open") View.GONE else View.VISIBLE
                } else {
                    binding.overviewCloseloop.visibility = View.GONE
                    binding.overviewLgsloop.visibility = View.GONE
                    binding.overviewOpenloop.visibility = View.GONE
                }
                binding.overviewEnable.visibility = View.GONE          //sp.getBoolean(R.string.key_usesuperbolus, false).toVisibility()
                binding.overviewDisable.visibility = View.VISIBLE
               if (!loopPlugin.isSuspended) {
                    binding.overviewSuspendHeader.text=resourceHelper.gs(R.string.suspendloop)
                    binding.overviewResume.visibility = View.GONE
                    binding.overviewSuspendButtons.visibility=View.VISIBLE
                    binding.overviewSuspend.visibility=View.VISIBLE
                } else {
                    if (!loopPlugin.isDisconnected) {
                        binding.overviewSuspendHeader.text = resourceHelper.gs(R.string.resumeloop)
                        binding.overviewResume.visibility = View.VISIBLE
                        binding.overviewSuspendButtons.visibility=View.GONE
                        binding.overviewSuspend.visibility=View.VISIBLE
                    } else
                        binding.overviewSuspend.visibility = View.GONE
                }
            } else {
                binding.overviewEnable.visibility = View.VISIBLE
                binding.overviewDisable.visibility = View.GONE
                binding.overviewSuspend.visibility = View.GONE
            }
            if (!loopPlugin.isDisconnected) {
                binding.overviewPumpHeader.text = resourceHelper.gs(R.string.disconnectpump)
                binding.overviewDisconnect15m.visibility = if (pumpDescription.tempDurationStep15mAllowed) View.VISIBLE else View.GONE
                binding.overviewDisconnect30m.visibility = if (pumpDescription.tempDurationStep30mAllowed) View.VISIBLE else View.GONE
                binding.overviewDisconnectButtons.visibility = View.VISIBLE
                binding.overviewReconnect.visibility = View.GONE
            } else {
                binding.overviewPumpHeader.text = resourceHelper.gs(R.string.reconnect)
                binding.overviewDisconnectButtons.visibility = View.GONE
                binding.overviewReconnect.visibility = View.VISIBLE
            }
        }
        val profile = profileFunction.getProfile()
        val profileStore = activePlugin.activeProfileInterface.profile

        if (profile == null || profileStore == null) {
            ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile))
            dismiss()
            return
        }

    }

    fun onClick_OkCancelEnabled(v: View): Boolean {
        var description = ""
        when(v.id) {
            R.id.overview_closeloop         -> description = resourceHelper.gs(R.string.closedloop)
            R.id.overview_lgsloop           -> description = resourceHelper.gs(R.string.lowglucosesuspend)
            R.id.overview_openloop          -> description = resourceHelper.gs(R.string.openloop)
            R.id.overview_disable           -> description = resourceHelper.gs(R.string.disableloop)
            R.id.overview_enable            -> description = resourceHelper.gs(R.string.enableloop)
{'fraction_non_alphanumeric': 0.08468859730179265, 'fraction_numerical': 0.002217704675660691, 'mean_word_length': 3.1834170854271355, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7391768', 'n_tokens_mistral': 5906, 'n_tokens_neox': 5603, 'n_words': 982}