/*!
 * 
 * Copyright (c) 2019-2020 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)      09-Feb-2021
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  27-Jan-2020
 * 
 */

// Qt
import QtQuick 2.12

//  Qml imports
import "qrc:/globals"
import "qrc:/components"
import "qrc:/pages/treatment/adjustments"
import "qrc:/pages/pretreatment/create"
import "qrc:/pages/posttreatment"

/*!
 * \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"

    stackView.initialItem   : _treatmentHome

    // ultrafiltration state information bar properties
    readonly property bool   isUFPaused         : vHDTreatmentStates.ufPaused
    readonly property bool   isUFOff            : vHDTreatmentStates.ufOff
    readonly property bool   isUFRunning        : vHDTreatmentStates.ufRunning
    readonly property bool   isUFCompleted      : vHDTreatmentStates.ufCompleted
    readonly property string ufInfoImageSource  : isUFPaused    ? "qrc:/images/iPauseGray" :
                                                  isUFOff       ? "qrc:/images/iOffGray"   :
                                                  isUFCompleted ? "qrc:/images/iDone"      : ""
    readonly property string ufInfoText         : isUFPaused    ? qsTr("Ultrafiltration is paused"    ) :
                                                  isUFOff       ? qsTr("Ultrafiltration is off"       ) :
                                                  isUFCompleted ? qsTr("Ultrafiltration is completed" ) : ""
    readonly property string ufInfoTextColor    : isUFPaused    ? "gray"  :
                                                  isUFOff       ? "gray"  :
                                                  isUFCompleted ? "lightgray" : ""

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

    // Components
    MainMenu                { id: _treatmentMenu
        y               : Variables.mainMenuHeight * -1
        position        : MainMenu.Position.Top
        hidden          : true
        titles          : [ qsTr("Back") , qsTr("Treatment") , qsTr("Trending") , qsTr("Settings") ]
        spacing         :  20
        leftPdding      :  20
        partitionWidth  : 100 // Todo Important : max width should be the width for all
        hasRightText    : true
        hasLogo         : true
    }

    // Blood Prime
    PostTreatmentBloodPrime         { id: _postTreatmentBloodPrime          } // only one page, no stack for now.
    PostTreatmentRinsebackStack     { id: _postTreatmentRinsebackStack      }
    PostTreatmentRecirculateStack   { id: _postTreatmentRecirculateStack    }
    PostTreatmentEndStack           { id: _postTreatmentEndStack            }

    TreatmentHome               { id:       _treatmentHome
        onTreatmentStarted      : push( _treatmentStart )
        onTreatmentCreated      : vTreatmentCreate.doSelectParameters()
    }

    TreatmentStart              { id:       _treatmentStart
        onBackClicked           : pop( _treatmentHome )
        onSectionFlowClicked    : {
            _treatmentAdjustmentFlow.open()
        }
        onSectionVitalsClicked: {
            // no page yet
        }
        onSectionPressuresClicked: {
            _treatmentAdjustmentPressuresLimits.open()
        }
        onSectionTimeClicked    : {
            _treatmentAdjustmentDuration.durationValue = vTreatmentTime.time_Total / 60 // minutes => hours
            _treatmentAdjustmentDuration.open()
        }
        onSectionUltrafiltrationClicked: {
            if ( isUFRunning ) {
                _treatmentAdjustmentUltrafiltrationStart .open()
            } else {
                _treatmentAdjustmentUltrafiltrationPaused.open()
            }
        }
    }

    PreTreatmentCreate          { id:       _pretreatmentCreate
        onBackClicked           : {vTreatmentCreate.doCancelSelectingParameters() }
        onContinueClicked       : {vTreatmentCreate.doFinishedCreate();  }
    }

    PreTreatmentConfirm         { id:      _pretreatmentConfirm
        onBackClicked           : {vTreatmentCreate.doCancelConfirmParameters()   }
        onConfirmClicked        : {vTreatmentCreate.doFinishedConfirm(); }
    }

    PreTreatmentPrime           { id:        _pretreatmentPrime
        onBackClicked           : {vTreatmentCreate.doRequestPop()       }
        onContinueClicked       : {vTreatmentCreate.doFinishedPrime();   }
    }

    PreTreatmentUltrafiltration { id:        _pretreatmentUltrafiltration
        onBackClicked           : {vTreatmentCreate.doRequestPop()       }
        onStartClicked          : {vTreatmentBegin.doCheckBLE()          }
    }

    //// Treatment Adjustment Dialogs
    TreatmentAdjustmentFlow     { id:       _treatmentAdjustmentFlow
        onCloseClicked          : close()
        onConfirmClicked        : vTreatmentAdjustmentFlows.doAdjustment(bloodFlowRateValue, dialysateFlowRateValue)
    }

    TreatmentAdjustmentPressuresLimits { id:       _treatmentAdjustmentPressuresLimits
        onCloseClicked              : close()
        onConfirmClicked            : vTreatmentAdjustmentPressuresLimits.doAdjustment(
                                          arterialPressureLowerBound ,
                                          arterialPressureUpperBound ,
                                          venousPressureLowerBound   ,
                                          venousPressureUpperBound
                                       )

        arterialPressureMinimum     : Variables.arterialValueMin
        arterialPressureLowerBound  : vTreatmentAdjustmentPressuresLimits.arterialLimitLow
        arterialPressureUpperBound  : vTreatmentAdjustmentPressuresLimits.arterialLimitHigh
        arterialPressureMaximum     : Variables.arterialValueMax

        venousPressureMinimum       : Variables.venousValueMin
        venousPressureLowerBound    : vTreatmentAdjustmentPressuresLimits.venousLimitLow
        venousPressureUpperBound    : vTreatmentAdjustmentPressuresLimits.venousLimitHigh
        venousPressureMaximum       : Variables.venousValueMax

        arterialPressureStep        : Variables.arterialLimitStep
        arterialPressureValue       : vTreatmentPressureOcclusion.arterialPressure

        venousPressureStep          : Variables.venousLimitStep
        venousPressureValue         : vTreatmentPressureOcclusion.venousPressure
    }

    TreatmentAdjustmentDuration { id:       _treatmentAdjustmentDuration
        onCloseClicked          : close()
        onConfirmClicked        : vTreatmentAdjustmentDuration.doAdjustment(durationValue)
    }

    TreatmentAdjustmentUltrafiltrationStart { id: _treatmentAdjustmentUltrafiltrationStart
        onCloseClicked          : close()
        onPauseClicked          : {
            // send pause to HD and wait.
            // if accepted close()
            // not accepted show error in notification
            vTreatmentAdjustmentUltrafiltrationState.doPause()
        }
    }

    TreatmentAdjustmentUltrafiltrationPaused { id: _treatmentAdjustmentUltrafiltrationPaused
        onCloseClicked          : close()
        onEditClicked           : {
            close()
            _treatmentAdjustmentUltrafiltrationEdit.reset() // reset the slider to minimum value position
            _treatmentAdjustmentUltrafiltrationEdit.open()
        }
        onResumeClicked         : {
            // send resume to HD and wait.
            // if accepted close()
            // not accepted show error in notification
            vTreatmentAdjustmentUltrafiltrationState.doResume()
        }
    }

    TreatmentAdjustmentUltrafiltrationEdit { id: _treatmentAdjustmentUltrafiltrationEdit
        onBackClicked           : {
            close()
            _treatmentAdjustmentUltrafiltrationPaused.open()
        }
        onNextClicked           : {
            // send Volume to HD and wait.
            // if accepted close()
            // not accepted show error in notification
            vTreatmentAdjustmentUltrafiltrationEdit.doAdjustment(vVolume)
        }
    }

    TreatmentAdjustmentUltrafiltrationConfirm { id: _treatmentAdjustmentUltrafiltrationConfirm
        onBackClicked           : {
            close()
            _treatmentAdjustmentUltrafiltrationEdit.open ()
        }
        onConfirmRateClicked    : {
            vTreatmentAdjustmentUltrafiltrationConfirm.doOptionRate(vVolume)
        }
        onConfirmDurationClicked: {
            vTreatmentAdjustmentUltrafiltrationConfirm.doOptionDuration(vVolume)
        }
    }


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

    Connections { target: vTreatmentAdjustmentUltrafiltrationInit
        onAdjustmentTriggered   : {
            // the maximum ultrafiltration volume has to be set/revert regardless
            vTreatmentUltrafiltration.maximum = vTreatmentAdjustmentUltrafiltrationInit.volume
            _pretreatmentUltrafiltration.ufVolume          = vTreatmentAdjustmentUltrafiltrationInit.volume
            // but only if it has been accepted it will navigate
            if (vTreatmentAdjustmentUltrafiltrationInit.adjustment_Accepted) {
                vTreatmentBegin.doStartTreatment()
            }
            else {
                _pretreatmentUltrafiltration.reasonText  = vTreatmentAdjustmentUltrafiltrationInit.text()
            }
        }
    }

    Connections { target: vTreatmentAdjustmentUltrafiltrationState
        onAdjustmentTriggered   : {
            if ( vTreatmentAdjustmentUltrafiltrationState.adjustment_Accepted ) {
                if (vHDTreatmentStates.ufPaused) { // handle screen regarding current accepted
                    _treatmentAdjustmentUltrafiltrationStart .close()
                    _treatmentAdjustmentUltrafiltrationPaused.open ()
                } else {
                    _treatmentAdjustmentUltrafiltrationPaused.close()
                }
            }
            else {
                if (vHDTreatmentStates.ufRunning) { // handle error messages regarding current accepted
                    _treatmentAdjustmentUltrafiltrationStart.notificationText = vTreatmentAdjustmentUltrafiltrationState.adjustment_ReasonText
                } else {
                    _treatmentAdjustmentUltrafiltrationPaused.notificationText = vTreatmentAdjustmentUltrafiltrationState.adjustment_ReasonText
                }
            }
        }
    }

    Connections { target: vTreatmentAdjustmentUltrafiltrationEdit
        onAdjustmentTriggered   : {
            if (vTreatmentAdjustmentUltrafiltrationEdit.adjustment_Accepted) {
                _treatmentAdjustmentUltrafiltrationConfirm.ultrafiltrationVolume    = vTreatmentAdjustmentUltrafiltrationEdit.volume
                _treatmentAdjustmentUltrafiltrationConfirm.treatmentDuration        = vTreatmentAdjustmentUltrafiltrationEdit.duration
                _treatmentAdjustmentUltrafiltrationConfirm.treatmentDurationDiff    = vTreatmentAdjustmentUltrafiltrationEdit.durationDiff
                _treatmentAdjustmentUltrafiltrationConfirm.ultrafiltrationRate      = vTreatmentAdjustmentUltrafiltrationEdit.rate
                _treatmentAdjustmentUltrafiltrationConfirm.ultrafiltrationRateDiff  = vTreatmentAdjustmentUltrafiltrationEdit.rateDiff
                _treatmentAdjustmentUltrafiltrationConfirm.ultrafiltrationRateOld   = vTreatmentAdjustmentUltrafiltrationEdit.rateOld

                _treatmentAdjustmentUltrafiltrationEdit   .close()
                _treatmentAdjustmentUltrafiltrationConfirm.reset()
                _treatmentAdjustmentUltrafiltrationConfirm.open ()
            } else {
                _treatmentAdjustmentUltrafiltrationEdit.notification.text = vTreatmentAdjustmentUltrafiltrationEdit.text()
            }
        }
    }

    Connections { target: vTreatmentAdjustmentUltrafiltrationConfirm
        onAdjustmentTriggered   : {
            if (vTreatmentAdjustmentUltrafiltrationConfirm.adjustment_Accepted) {
                vTreatmentUltrafiltration.maximum                            = vTreatmentAdjustmentUltrafiltrationConfirm.volume
                _treatmentAdjustmentUltrafiltrationConfirm.close()
            } else {
                _treatmentAdjustmentUltrafiltrationConfirm.notification.text = vTreatmentAdjustmentUltrafiltrationConfirm.text()
            }
        }
    }

    Connections { target: vTreatmentAdjustmentPressuresLimits
        onAdjustmentTriggered   : {
            // 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: vTreatmentCreate
        onShowCreate           : { push(_pretreatmentCreate)  }
        onShowConfirm          : { push(_pretreatmentConfirm) }
        onShowPrime            : { push(_pretreatmentPrime)   }
        onShowBegin            : { push(_pretreatmentUltrafiltration)   }
        onPop                  : { pop()                   }
        onShowTreatmentStart   : { push(_treatmentStart)   }
    }

    // the back is more flixible regarding our current design
    // and it's easier(or may not need) to modify later if required.
    // and is more optimized and will never leave screen empty
    // also with what ever order they have been push with the reverse/correct animation will be poped or pushed.
    Connections { target: vHDTreatmentStates
        // Blood Prime
        onTxBloodPrimeChanged   : { if ( vtxBloodPrime      ) { page( _postTreatmentBloodPrime          )}}
        onBpRampChanged         : { if ( vbpRamp            ) { /* No action defined yet */              }}

        // in-Treatmet
        onTxDialysisChanged     : { if ( vtxDialysis        ) { page( _treatmentStart                   )}}

        onTxRinsebackChanged    : { if ( vtxRinseback       ) { page( _postTreatmentRinsebackStack      )}}
        onTxRecirculateChanged  : { if ( vtxRecirculate     ) { page( _postTreatmentRecirculateStack    )}}
        onTxEndChanged          : { if ( vtxEnd             ) { page( _postTreatmentEndStack            )}}

        // Treatment Stop
        onTxStopChanged         : { if ( vtxStop            ) { page( _treatmentStart                   )}}
        onTsRecirculateChanged  : { if ( vtsRecirculate     ) { /* No action defined yet */              }}
        onTsRecirculateNoChanged: { if ( vtsRecirculateNo   ) { /* No action defined yet */              }}
    }

    Connections { target: vTreatmentBegin
        onDidConfirmReadyToStartTreament: {
            vTreatmentAdjustmentUltrafiltrationInit.doAdjustment(_pretreatmentUltrafiltration.ufVolume);
        }
    }
}
