/*!
 *
 * Copyright (c) 2020-2023 Diality Inc. - All Rights Reserved.
 * \copyright
 * THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN
 * WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER.
 *
 * \file    TreatmentStack.qml
 * \author  (last)      Behrouz NematiPour
 * \date    (last)      28-Feb-2023
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  27-Jan-2020
 *
 */

// Qt
import QtQuick 2.12
//import QtCharts 2.3

//  Qml imports
import "qrc:/globals"
import "qrc:/components"
import "qrc:/compounds"
import "qrc:/pages/treatment/adjustments"

/*!
 * \brief   TreatmentStack is the screen
 * which contains the main stack for all the Trearment screens
 * This is the screen which will be show up when "Treatment" option
 * is selected from the main menu.
 */
StackItem { id : _root
    objectName: "TreatmentStack"

    onVisibleChanged        : { // this should never happen by design, but in tests it can easily happen and will block the screen touch.
        _treatmentAdjustmentFlow            .close()
        _vitalEntry                         .close( true ) // vQuit == true
        _treatmentAdjustmentPressuresLimits .close()
        _treatmentAdjustmentDuration        .close()
        _treatmentUltrafiltrationItem       .close()
    }

    stackView.initialItem   : null

    // ultrafiltration state information bar properties
    readonly property bool   isUFPaused         : vHDTreatmentStates.ufPaused
    readonly property bool   isUFRunning        : vHDTreatmentStates.ufRunning
    readonly property string ufInfoImageSource  : isUFPaused    ? "qrc:/images/iPauseGray" : ""
    readonly property string ufInfoText         : isUFPaused    ? qsTr("Ultrafiltration Paused"    ) : ""
    readonly property string ufInfoTextColor    : isUFPaused    ? "gray"  : ""

    readonly property bool   isSBInProgress     : ( vHDTreatmentStates.sbRunning || vHDTreatmentStates.sbWaitPump )

    // Components
    MainMenu            { id: _treatmentMenu
        y               : Variables.mainMenuHeight * -1
        position        : MainMenu.Position.Top
        hidden          : true
        titles          : [ qsTr("Treatment") , qsTr("Trending") , qsTr("Settings") ]
        spacing         :  20
        leftPdding      :  20
        rightPdding     :  50
        partitionWidth  : 100 // Todo Important : max width should be the width for all bottons
        hasRightText    : true
        hasLogo         : true
        /* ----- TEST: Under the test code, for the plotting of the items -----
        onCurrentIndexChanged: {
            console.debug(currentIndex)
            if (currentIndex == 1) push(_treatmentTrending)
            if (currentIndex == 0) pop()
        }
        */
    }

    TreatmentBloodPrime         { id: _treatmentBloodPrime          }
    TreatmentUltrafiltrationItem{ id: _treatmentUltrafiltrationItem }
    TreatmentHome               { id: _treatmentHome                }

    Connections                 { target: _treatmentHome
        function onSectionFlowClicked               ( vValue ) {
            _treatmentAdjustmentFlow.open()
        }
        function onSectionVitalsClicked             ( vValue ) {
            _vitalEntry.open()
        }
        function onSectionPressuresClicked          ( vValue ) {
            _treatmentAdjustmentPressuresLimits.open()
        }
        function onSectionTimeClicked               ( vValue ) {
            _treatmentAdjustmentDuration.durationValue = vTreatmentTime.time_Total / 60 // minutes => hours
            _treatmentAdjustmentDuration.open()
        }
        function onSectionUltrafiltrationClicked    ( vValue ) {
            _treatmentUltrafiltrationItem.open()
        }
    }

    ScreenItem                  { id: _treatmentTrending    }

    //// Treatment Adjustment Dialogs
    TreatmentAdjustmentFlow     { id:       _treatmentAdjustmentFlow    }
    TreatmentAdjustmentPressuresLimits  { id:       _treatmentAdjustmentPressuresLimits
        arterialPressureMinimum     : vTreatmentRanges.arterialPressureMonitorMin
        arterialPressureMaximum     : vTreatmentRanges.arterialPressureMonitorMax
        venousPressureMinimum       : vTreatmentRanges.venousPressureMonitorMin
        venousPressureMaximum       : vTreatmentRanges.venousPressureMonitorMax

        arterialPressureLowerBound  : vTreatmentAdjustmentPressuresLimits.arterialLimitLow
        arterialPressureUpperBound  : vTreatmentAdjustmentPressuresLimits.arterialLimitHigh
        venousPressureLowerBound    : vTreatmentAdjustmentPressuresLimits.venousLimitLow
        venousPressureUpperBound    : vTreatmentAdjustmentPressuresLimits.venousLimitHigh

        arterialPressureStep        : vTreatmentRanges.arterialPressureLimitLowRes
        arterialPressureValue       : vTreatmentPressureOcclusion.arterialPressure

        venousPressureStep          : vTreatmentRanges.venousPressureLimitLowRes
        venousPressureValue         : vTreatmentPressureOcclusion.venousPressure
    }

    Connections                 { target:   _treatmentAdjustmentFlow
        function onConfirmClicked                   ( vValue ) { vTreatmentAdjustmentFlows.doAdjustment(
                                            _treatmentAdjustmentFlow.bloodFlowRateValue     ,
                                            _treatmentAdjustmentFlow.dialysateFlowRateValue )
        }
    }
    Connections                 { target:   _treatmentAdjustmentPressuresLimits
        function onConfirmClicked                   ( vValue ) { vTreatmentAdjustmentPressuresLimits.doAdjustment(
                                            _treatmentAdjustmentPressuresLimits.arterialPressureLowerBound  ,
                                            _treatmentAdjustmentPressuresLimits.arterialPressureUpperBound  ,
                                            _treatmentAdjustmentPressuresLimits.venousPressureLowerBound    ,
                                            _treatmentAdjustmentPressuresLimits.venousPressureUpperBound    )
        }
    }

    TreatmentAdjustmentDuration { id:       _treatmentAdjustmentDuration    }
    Connections                 { target:   _treatmentAdjustmentDuration
        function onConfirmClicked                   ( vValue ) { vTreatmentAdjustmentDuration.doAdjustment(
                                            _treatmentAdjustmentDuration.durationValue                      )
        }
    }

    EntryDialog                 { id:       _vitalEntry
        function update(vSystolic, vDiastolic ,vHeartRate) {
            _bphrEntry.systolic   = vSystolic   ? vSystolic  : ""
            _bphrEntry.diastolic  = vDiastolic  ? vDiastolic : ""
            _bphrEntry.heartRate  = vHeartRate  ? vHeartRate : ""
        }

        titleText               : qsTr("VITALS")
        confirmEnabled          : _bphrEntry.isValid
        onConfirmClicked        : {
            _vitalEntry.close()
            vTreatmentVitals.doConfirm(
                        _bphrEntry.systolic   ,
                        _bphrEntry.diastolic  ,
                        _bphrEntry.heartRate
                        )
        }

        onCloseClicked          : {
            vTreatmentVitals.doSkip() // only for logging
        }

        onOpened                : {
            vTreatmentVitals.doTimerStop() // Can't be moved to C++, and has to be handled here because it can manually being opened by the user
            _bphrEntry.setFocus()
        }

        onClosed                : {
            if ( ! vQuit )
                vTreatmentVitals.doTimerStart()
        }

        BPHREntry { id          : _bphrEntry
            contentRectHeight   : _vitalEntry.contentRect.height
        }

        Connections { target: vTreatmentVitals
            function onDidTrigger       ( vSystolic, vDiastolic, vHeartRate ) {
                if  ( vTreatmentVitals.enableDialog ) {
                    _vitalEntry.update  ( vSystolic, vDiastolic, vHeartRate )
                    _vitalEntry.open    ()
                }
            }
        }
    }

    // ---------- Manages Responses ----------
    Connections { target: vTreatmentAdjustmentDuration
        function onAdjustmentTriggered              ( vValue ) {
            if ( vTreatmentAdjustmentDuration.adjustment_Accepted ) {
                vTreatmentUltrafiltration.maximum               = vTreatmentAdjustmentDuration.ultrafiltration
                _treatmentAdjustmentDuration.accept()
            } else {
                _treatmentAdjustmentDuration.durationValue      = vTreatmentAdjustmentDuration.duration;
                _treatmentAdjustmentDuration.notification.text  = vTreatmentAdjustmentDuration.text();
            }
        }
    }

    Connections { target: vTreatmentAdjustmentPressuresLimits
        function onAdjustmentTriggered              ( vValue ) {
            // values have to be update even when rejected HD is reverting back the values.
            // if accepted will be updated for later [may need refresh later]
            _treatmentAdjustmentPressuresLimits.arterialPressureLowerBound = vTreatmentAdjustmentPressuresLimits.arterialLimitLow
            _treatmentAdjustmentPressuresLimits.arterialPressureUpperBound = vTreatmentAdjustmentPressuresLimits.arterialLimitHigh
            _treatmentAdjustmentPressuresLimits.venousPressureLowerBound   = vTreatmentAdjustmentPressuresLimits.venousLimitLow
            _treatmentAdjustmentPressuresLimits.venousPressureUpperBound   = vTreatmentAdjustmentPressuresLimits.venousLimitHigh

            if (vTreatmentAdjustmentPressuresLimits.adjustment_Accepted) {
                _treatmentAdjustmentPressuresLimits.close()
            }
            else {
                _treatmentAdjustmentPressuresLimits.notification.text = vTreatmentAdjustmentPressuresLimits.text()
            }
        }
    }

    Connections { target: vHDOperationMode
        // The initail screen should be the Blood Prime, since that one is the earlier state in the list.
        // also since it is being used in two stacks In-Treatment and also in End-Treatmet is has been defined in the MainStack.
        function onInTreatmentChanged               ( vValue ) { page( _treatmentBloodPrime  , vValue   )}
    }

    Connections { target: _treatmentBloodPrime
        function onVisibleChanged                   ( vValue ) {
            if (_treatmentBloodPrime.visible) {
                _treatmentMenu.hidden = true
            }
        }
    }

    Connections { target: vHDTreatmentStates
        // in-Treatmet
        function onTxBloodPrimeChanged              ( vValue ) { page( _treatmentBloodPrime  , vValue   )}
        function onTxDialysisChanged                ( vValue ) { page( _treatmentHome        , vValue   )}
    }

    Connections { target: _mainHome
        function onStartTreatment                   ( vValue ) { page( _treatmentHome                   )}
    }
}
