/*!
 *
 * Copyright (c) 2020-2024 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)      Vy
 * \date    (last)      14-Jun-2023
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  27-Jan-2020
 *
 */

// Qt
import QtQuick 2.12

//  Qml imports
import "qrc:/components"
import "qrc:/compounds"
import "qrc:/dialogs"
import "qrc:/globals"
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()

        if (! visible) {
            _headerBar.menuHidden = true
        }
    }

    stackView.initialItem   : null

    // ultrafiltration state information bar properties
    readonly property bool   isUFPaused         : vTDTreatmentStates.ufPaused
    readonly property bool   isUFRunning        : vTDTreatmentStates.ufRunning
    readonly property bool   isTreatmentPaused  : vTDTreatmentStates.txStop

    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     : ( vTDTreatmentStates.sbRunning || vTDTreatmentStates.sbWaitPump )

    readonly property bool isDialogOpened : _treatmentAdjustmentFlow            .visible
                                         || _treatmentAdjustmentPressuresLimits .visible
                                         || _treatmentAdjustmentDuration        .visible
                                         || _treatmentUltrafiltrationItem       .visible

    property int headerMenuIndex: _headerBar.headerMenuIndex

    onHeaderMenuIndexChanged: {
        if ( _root.headerMenuIndex === 2)     page(_treatmentHeparin)
        if ( _root.headerMenuIndex === 1)     page(_treatmentTrends)
        if ( _root.headerMenuIndex === 0)     pop(null) // unwind stack
    }

    // Components
    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 ) {
            //DEBUG: console.log("time total minutes: " + vTreatmentTime.time_Total / 60 )
            _treatmentAdjustmentDuration.setDurationValue(vTreatmentTime.time_Total / 60) // minutes => hours
            _treatmentAdjustmentDuration.open()
        }
        function onSectionUltrafiltrationClicked    ( vValue ) {
            _treatmentUltrafiltrationItem.open()
        }
    }

    ScreenItem                  { id: _treatmentTrends      } // TODO: make me!
    ScreenItem                  { id: _treatmentHeparin     } // TODO: make me!

    //// Treatment Adjustment Dialogs
    TreatmentAdjustmentFlow             { id:       _treatmentAdjustmentFlow    }
    TreatmentAdjustmentPressuresLimits  { id:       _treatmentAdjustmentPressuresLimits    }

    Connections                 { target:   _treatmentAdjustmentFlow
        function onConfirmClicked                   ( vValue ) { vTreatmentAdjustmentFlows.doAdjustment(
                                            _treatmentAdjustmentFlow.bloodFlowRateValue     ,
                                            _treatmentAdjustmentFlow.dialysateFlowRateValue )
        }
    }
    Connections                 { target:   _treatmentAdjustmentPressuresLimits
        function onConfirmClicked                   ( vValue ) { vTreatmentAdjustmentPressuresLimits.doAdjustment(
                                            _treatmentAdjustmentPressuresLimits.arterialPressureLimitWindow ,
                                            _treatmentAdjustmentPressuresLimits.venousPressureLimitWindow   ,
                                            _treatmentAdjustmentPressuresLimits.venousPressureLimitAsymtrc  )
        }
    }

    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
                        )
            _treatmentHome.logVitalTime()
        }

        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

        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.setDurationValue(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.arterialPressureLimitWindow = vTreatmentAdjustmentPressuresLimits.arterialPressureLimitWindow
            _treatmentAdjustmentPressuresLimits.venousPressureLimitWindow   = vTreatmentAdjustmentPressuresLimits.venousPressureLimitWindow
            _treatmentAdjustmentPressuresLimits.venousPressureLimitAsymtrc  = vTreatmentAdjustmentPressuresLimits.venousPressureLimitAsymtrc

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

    Connections { target: vTDOpMode
        // 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) {
                _headerBar.menuHidden = true
            }
        }
    }

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

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