/*!
 *
 * 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)      28-Feb-2021
 * \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"

    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
        partitionWidth  : 100 // Todo Important : max width should be the width for all bottons
        hasRightText    : true
        hasLogo         : true
        onCurrentIndexChanged: {
            console.debug(currentIndex)
            if (currentIndex == 1) push(_treatmentTrending)
            if (currentIndex == 0) pop()
        }
    }

    TreatmentBloodPrime         { id: _treatmentBloodPrime          }
    TreatmentUltrafiltrationItem{ id: _treatmentUltrafiltrationItem }
    TreatmentHome               { id: _treatmentHome
        onSectionFlowClicked    : {
            _treatmentAdjustmentFlow.open()
        }
        onSectionVitalsClicked  : {
            _vitalEntry.open()
        }
        onSectionPressuresClicked: {
            _treatmentAdjustmentPressuresLimits.open()
        }
        onSectionTimeClicked    : {
            _treatmentAdjustmentDuration.durationValue = vTreatmentTime.time_Total / 60 // minutes => hours
            _treatmentAdjustmentDuration.open()
        }
        onSectionUltrafiltrationClicked: {
            _treatmentUltrafiltrationItem.open()
        }
    }

    ScreenItem                  { id: _treatmentTrending
/* ----- TEST: Under the test code, for the plotting of the items -----
        Timer { id: _timer
            property real x1: 0
            property real x2: 0
            interval: 500
            running: _treatmentTrending.visible
            repeat: true
            onTriggered: {
                x1 = x1 + 1
                x2 = x2 + 0.1

                var r = Math.random()
                _lineSerries1.append(x1, r * 10 )
                _lineSerries2.append(x2, r      )
            }
        }
        Column {
            anchors.fill: parent
            anchors.topMargin: Variables.mainMenuHeight
            Slider { id : _zoomSlider
                width   : parent.width
                minimum : 0
                maximum : 2
                step    : 0.1
                value   : 0
                onValueChanged: _chartView.zoom(value)
            }
            TouchRect {
                width   : 50
                height  : 50
                onClicked: _chartView.zoomReset()
            }

            ChartView { id: _chartView
                title: "Line"
                width: parent.width
                height: parent.height - _zoomSlider.height
                antialiasing: true
                backgroundColor: Colors.transparent

                legend.labelColor: Colors.white

                ValueAxis { id: xAxis1
                    color: Colors.white
                    min: 0
                    max: _timer.x1
                }
                ValueAxis { id: yAxis1
                    color: Colors.white
                    min: 0
                    max: 10
                }
                SplineSeries { id: _lineSerries1
                    name: "LineSeries"
                    axisX: xAxis1
                    axisY: yAxis1
                }
                ValueAxis { id: xAxis2
                    color: Colors.white
                    min: 0
                    max: _timer.x2
                }
                ValueAxis { id: yAxis2
                    color: Colors.white
                    labelsColor: Colors.red
                    min: 0
                    max: 10
                }
                SplineSeries { id: _lineSerries2
                    name: "LineSeries"
                    axisX: xAxis2
                    axisY: yAxis2
                }
            }
        }
*/
    }

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

    EntryDialog                 { id:       _vitalEntry
        titleText               : qsTr("VITALS")
        autoHide                : true
        autoHideDuration        : vTreatmentVitals.timeout * 60000 // min => ms
        confirmEnabled          : _bphrEntry.isValid
        onConfirmClicked        : {
            vTreatmentVitals.doConfirm(
                        _bphrEntry.systolic   ,
                        _bphrEntry.diastolic  ,
                        _bphrEntry.heartRate
                        )
            _vitalEntry.close()
        }

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

        onAutoHidden            :
            vTreatmentVitals.doTimeout() // only for logging

        BPHREntry { id          : _bphrEntry
            contentRectHeight   : _vitalEntry.contentRect.height
            onClicked           : {
                _vitalEntry.autoHideCancel = true
            }
        }
    }

    TreatmentAdjustmentPressuresLimits { id:       _treatmentAdjustmentPressuresLimits
        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
        onConfirmClicked        : vTreatmentAdjustmentDuration.doAdjustment(durationValue)
    }

    // ---------- 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: 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: 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.
        onInTreatmentChanged    : { page( _treatmentBloodPrime  , vinTreatment      )}
    }

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

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

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

    Connections { target: vTreatmentVitals
        onDidTrigger            : { _vitalEntry.open()                               }
    }

}
