/*!
 *
 * 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    PreTreatmentCreate.qml
 * \author  (last)      Behrouz NematiPour
 * \date    (last)      01-Mar-2021
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  27-Jan-2020
 *
 */

// Qt
import QtQuick 2.12
import QtQuick.Controls 2.12 // ScrollBar

// Project
//  Qml imports
import "qrc:/globals"
import "qrc:/components"
import "qrc:/pages/pretreatment"

/*!
 * \brief   Pre-Treatment create screen
 * \details which contains the components to let user set values of the treatment parameters.
 */
PreTreatmentBase { id: _root
    objectName: "_PreTreatmentCreate" // SquishQt testability

    header.confirmEnabled: vTreatmentCreate.continueEnabled

    function setInteractive(isInteractive) {
        _flickable.interactive = isInteractive
    }

    ScrollBar {
        flickable   : _flickable
        anchors.fill: _flickable
        anchors.rightMargin : Variables.minVGap
    }

    Flickable { id: _flickable
        objectName: "TreatmentCreateFlickable"
        clip: true
        anchors {
            top             : _root.title.bottom
            topMargin       : Variables.minVGap
            bottom          : _root.bottom
            bottomMargin    : Variables.notificationHeight + Variables.minVGap
            horizontalCenter: parent.horizontalCenter
        }
        width: parent.width
        contentWidth: parent.width
        contentHeight: _column.implicitHeight
        flickDeceleration: Variables.createTreatmentFlickableDeceleration

        Column { id: _column
            spacing: Variables.treatmentSpacing
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.fill: parent

            Text { id: _titleTextPrescription
                anchors.horizontalCenter: parent.horizontalCenter
                text: qsTr("PRESCRIPTION")
                color: Colors.textMain
                font.pixelSize: Fonts.fontPixelButton
                font.bold: true
            }

            SliderCreateTreatment { id: _bloodFlowRate
                objectName: "_bloodFlowRate"
                value   : vTreatmentCreate.bloodFlowRate
                min     : vTreatmentCreate.bloodFlowRateMin
                max     : vTreatmentCreate.bloodFlowRateMax
                step    : vTreatmentCreate.bloodFlowRateRes
                text    : qsTr("Blood Flow Rate")
                units   : Variables.unitTextFlowRate
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.bloodFlowRate = value
                }
                onReleased: {
                    vTreatmentCreate.bloodFlowRate = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _dialysateFlowRate
                objectName: "_dialysateFlowRate"
                value   : vTreatmentCreate.dialysateFlowRate
                min     : vTreatmentCreate.dialysateFlowRateMin
                max     : vTreatmentCreate.dialysateFlowRateMax
                step    : vTreatmentCreate.dialysateFlowRateRes
                text    : qsTr("Dialysate Flow Rate")
                units   : Variables.unitTextFlowRate
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.dialysateFlowRate = value
                }
                onReleased: {
                    vTreatmentCreate.dialysateFlowRate = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _duration
                objectName: "_duration"
                value   : vTreatmentCreate.duration
                min     : vTreatmentCreate.durationMin
                max     : vTreatmentCreate.durationMax
                step    : vTreatmentCreate.durationRes
                text    : qsTr("Duration")
                units   : Variables.unitTextDuration
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.duration = value
                }
                onReleased: {
                    vTreatmentCreate.duration = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _heparinDispensingRate
                objectName: "_heparinDispensingRate"
                value   : vTreatmentCreate.heparinDispensingRate
                min     : vTreatmentCreate.heparinDispensingRateMin
                max     : vTreatmentCreate.heparinDispensingRateMax
                step    : vTreatmentCreate.heparinDispensingRateRes
                text    : qsTr("Heparin Dispensing Rate")
                units   : Variables.unitTextDispencingRate
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.heparinDispensingRate = value
                }
                onReleased: {
                    vTreatmentCreate.heparinDispensingRate = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _heparinBolusVolume
                objectName: "_heparinBolusVolume"
                value   : vTreatmentCreate.heparinBolusVolume
                min     : vTreatmentCreate.heparinBolusVolumeMin
                max     : vTreatmentCreate.heparinBolusVolumeMax
                step    : vTreatmentCreate.heparinBolusVolumeRes
                text    : qsTr("Heparin Bolus Volume")
                units   : Variables.unitTextFluid
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.heparinBolusVolume = value
                }
                onReleased: {
                    vTreatmentCreate.heparinBolusVolume = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _heparinStopTime
                objectName: "_heparinStopTime"
                value   : vTreatmentCreate.heparinStopTime
                min     : vTreatmentCreate.heparinStopTimeMin
                max     : vTreatmentCreate.heparinStopTimeMax
                step    : vTreatmentCreate.heparinStopTimeRes
                text    : qsTr("Heparin Stop Time")
                units   : Variables.unitTextDuration
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.heparinStopTime = value
                }
                onReleased: {
                    vTreatmentCreate.heparinStopTime = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _salineBolus
                objectName: "_salineBolus"
                value   : vTreatmentCreate.salineBolusVolume
                min     : vTreatmentCreate.salineBolusVolumeMin
                max     : vTreatmentCreate.salineBolusVolumeMax
                step    : vTreatmentCreate.salineBolusVolumeRes
                text    : "Saline Bolus"
                units   : Variables.unitTextFluid
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.salineBolusVolume = value
                }
                onReleased: {
                    vTreatmentCreate.salineBolusVolume = value
                    setInteractive(true)
                }
            }

            Text { id: _titleTextOperation
                anchors.horizontalCenter: parent.horizontalCenter
                text: qsTr("OPERATING  PARAMETERS")
                color: Colors.textMain
                font.pixelSize: Fonts.fontPixelButton
                font.bold: true
            }

            GridSelection { id: _acidConcentrate
                objectName  : "_acidConcentrateRect"
                name        : qsTr("Acid Concentrate")
                buttonNames : vTreatmentCreate.acidConcentrateOptions
                onButtonClicked: {
                    vTreatmentCreate.acidConcentrate = selectedIndex
                }
            }

            GridSelection { id: _bicarbonateConcentrate
                objectName  : "_bicarbonateConcentrateRect"
                name        : qsTr("Bicarbonate Concentrate")
                numRows: 1
                numCols: 2
                buttonNames: vTreatmentCreate.bicarbonateConcentrateOptions
                onButtonClicked: {
                    vTreatmentCreate.bicarbonateConcentrate = selectedIndex
                }
            }

            GridSelection { id: _dialyzerType
                objectName: "_dialyzerTypeRect"
                name: qsTr("Dialyzer Type")
                numRows: 3
                numCols: 2
                buttonNames: vTreatmentCreate.dialyzerTypeOptions
                onButtonClicked: {
                    vTreatmentCreate.dialyzerType = selectedIndex
                }
            }

            SliderCreateTreatment { id: _dialysateTemperature
                objectName: "_dialysateTemperature"
                value   : vTreatmentCreate.dialysateTemp
                min     : vTreatmentCreate.dialysateTempMin
                max     : vTreatmentCreate.dialysateTempMax
                step    : vTreatmentCreate.dialysateTempRes
                text    : qsTr("Dialysate Temperature")
                units   : Variables.unitTextTemperature
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.dialysateTemp = value
                }
                onReleased: {
                    vTreatmentCreate.dialysateTemp = value
                    setInteractive(true)
                }
            }

            Column { id: _arterialColumn
                spacing: 45
                anchors.horizontalCenter: parent.horizontalCenter
                Text { id: _arterialLabel
                    visible : true
                    color   : Colors.textMain
                    text: qsTr("Arterial Pressure Limits") + " " + "(" + Variables.unitTextBloodPressure + ")"
                    font.pixelSize  : Fonts.fontPixelFluidText
                    anchors.left    : _arterialPressureLimits.left
                }
                RangeSlider { id: _arterialPressureLimits
                    objectName: "_arterialPressureLimitsSlider"
                    // dimension
                    height      : 5
                    width       : Variables.createTreatmentSliderWidth
                    diameter    : Variables.sliderCircleDiameter
                    anchors.horizontalCenter: parent.horizontalCenter
                    ticks       : true
                    stepSnap    : true
                    hasAdjusted : true

                    // Texts
                    lowerText.visible           : true
                    lowerText.font.pixelSize    : Fonts.fontPixelFluidText
                    lowerText.font.bold         : false
                    lowerText.anchors.topMargin : -50
                    lowerTextHorizontalCenter   : true

                    upperText.visible           : true
                    upperText.font.pixelSize    : Fonts.fontPixelFluidText
                    upperText.font.bold         : false
                    upperText.anchors.topMargin : -50
                    upperTextHorizontalCenter   : true

                    minText.visible             : true
                    // minText.font.pixelSize      : Fonts.fontPixelFluidText
                    minText.font.bold           : false
                    minVerticalEdgeVisible      : false

                    maxText.visible             : true
                    // maxText.font.pixelSize      : Fonts.fontPixelFluidText
                    maxText.font.bold           : false
                    maxVerticalEdgeVisible      : false

                    // Ranges
                    step                : Variables.arterialLimitStep
                    gapValue            : Variables.arterialLimitGap
                    minimum             : vTreatmentCreate.arterialPressureLimitLowMin
                    maximum             : vTreatmentCreate.arterialPressureLimitHighMax
                    minValue            : vTreatmentCreate.arterialPressureLimitLowMin
                    maxValue            : vTreatmentCreate.arterialPressureLimitHighMax
                    minValueLowerBound  : vTreatmentCreate.arterialPressureLimitLowMin
                    minValueUpperBound  : vTreatmentCreate.arterialPressureLimitLowMax
                    maxValueLowerBound  : vTreatmentCreate.arterialPressureLimitHighMin
                    maxValueUpperBound  : vTreatmentCreate.arterialPressureLimitHighMax
                    // scroll handling and value updates
                    onPressed : { setInteractive(false) }
                    onDragged : { setInteractive(false) }
                    onReleased: { setInteractive(true ) }
                    onMinValueChanged: { if ( minAdjusted ) vTreatmentCreate.arterialPressureLimitLow  = minValue }
                    onMaxValueChanged: { if ( maxAdjusted ) vTreatmentCreate.arterialPressureLimitHigh = maxValue }
                    onClicked        : { if ( minAdjusted ) vTreatmentCreate.arterialPressureLimitLow  = minValue
                                         if ( maxAdjusted ) vTreatmentCreate.arterialPressureLimitHigh = maxValue }
                }
            }

            Column { id: _venousColumn
                spacing: 45
                anchors.horizontalCenter: parent.horizontalCenter
                Text { id: _venousLabel
                    visible : true
                    color   : Colors.textMain
                    text: qsTr("Venous Pressure Limits") + " " + "(" + Variables.unitTextBloodPressure + ")"
                    font.pixelSize  : Fonts.fontPixelFluidText
                    anchors.left    : _venousPressureLimits.left
                }
                RangeSlider { id: _venousPressureLimits
                    objectName: "_venousPressureLimitsSlider"
                    // dimension
                    height      : 5
                    width       : Variables.createTreatmentSliderWidth
                    diameter    : Variables.sliderCircleDiameter
                    anchors.horizontalCenter: parent.horizontalCenter
                    ticks       : true
                    stepSnap    : true
                    hasAdjusted : true

                    // Texts
                    lowerText.visible           : true
                    lowerText.font.pixelSize    : Fonts.fontPixelFluidText
                    lowerText.font.bold         : false
                    lowerText.anchors.topMargin : -50
                    lowerTextHorizontalCenter   : true

                    upperText.visible           : true
                    upperText.font.pixelSize    : Fonts.fontPixelFluidText
                    upperText.font.bold         : false
                    upperText.anchors.topMargin : -50
                    upperTextHorizontalCenter   : true

                    minText.visible             : true
                    // minText.font.pixelSize      : Fonts.fontPixelFluidText
                    minText.font.bold           : false
                    minVerticalEdgeVisible      : false

                    maxText.visible             : true
                    // maxText.font.pixelSize      : Fonts.fontPixelFluidText
                    maxText.font.bold           : false
                    maxVerticalEdgeVisible      : false

                    // Ranges
                    step                : Variables.arterialLimitStep
                    gapValue            : Variables.arterialLimitGap
                    minimum             : vTreatmentCreate.venousPressureLimitLowMin
                    maximum             : vTreatmentCreate.venousPressureLimitHighMax
                    minValue            : vTreatmentCreate.venousPressureLimitLowMin
                    maxValue            : vTreatmentCreate.venousPressureLimitHighMax
                    minValueLowerBound  : vTreatmentCreate.venousPressureLimitLowMin
                    minValueUpperBound  : vTreatmentCreate.venousPressureLimitLowMax
                    maxValueLowerBound  : vTreatmentCreate.venousPressureLimitHighMin
                    maxValueUpperBound  : vTreatmentCreate.venousPressureLimitHighMax
                    // scroll handling and value updates
                    onPressed : { setInteractive(false) }
                    onDragged : { setInteractive(false) }
                    onReleased: { setInteractive(true ) }
                    onMinValueChanged: { if ( minAdjusted ) vTreatmentCreate.venousPressureLimitLow  = minValue }
                    onMaxValueChanged: { if ( maxAdjusted ) vTreatmentCreate.venousPressureLimitHigh = maxValue }
                    onClicked        : { if ( minAdjusted ) vTreatmentCreate.venousPressureLimitLow  = minValue
                                         if ( maxAdjusted ) vTreatmentCreate.venousPressureLimitHigh = maxValue }
                }
            }

            SliderCreateTreatment { id: _bloodPressureMeasurementInterval
                objectName: "_bloodPressureMeasurementInterval"
                value   : vTreatmentCreate.bloodPressureMeasureInterval
                min     : vTreatmentCreate.bloodPressureMeasureIntervalMin
                max     : vTreatmentCreate.bloodPressureMeasureIntervalMax
                step    : vTreatmentCreate.bloodPressureMeasureIntervalRes
                text    : qsTr("Blood Pressure Measurement Interval")
                units   : Variables.unitTextDuration
                stepSnap: true
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.bloodPressureMeasureInterval = value
                }
                onReleased: {
                    vTreatmentCreate.bloodPressureMeasureInterval = value
                    setInteractive(true)
                }
            }

            SliderCreateTreatment { id: _rinsebackFlowRate
                objectName: "_rinsebackFlowRate"
                value   : vTreatmentCreate.rinsebackFlowRate
                min     : vTreatmentCreate.rinsebackFlowRateMin
                max     : vTreatmentCreate.rinsebackFlowRateMax
                step    : vTreatmentCreate.rinsebackFlowRateRes
                text    : qsTr("Rinseback Flow Rate")
                units   : Variables.unitTextFlowRate
                stepSnap: true
                onPressed: {
                    setInteractive(false)
                    vTreatmentCreate.rinsebackFlowRate = value
                }
                onReleased: {
                    vTreatmentCreate.rinsebackFlowRate = value
                    setInteractive(true)
                }
            }
            Item {
                width   : 50
                height  : 50
            }
        }
    }

    Connections { target: vTreatmentCreate
        onResetCreateTreatment: {
            _bloodFlowRate.isActive = false
            _dialysateFlowRate.isActive = false
            _duration.isActive = false
            _heparinDispensingRate.isActive = false

            _heparinBolusVolume.isActive = false
            _heparinStopTime.isActive = false

            _salineBolus.isActive = false
            _acidConcentrate.setActive(false)
            _bicarbonateConcentrate.setActive(false)
            _dialyzerType.setActive(false)

            _dialysateTemperature.isActive = false
            _bloodPressureMeasurementInterval.isActive = false
            _rinsebackFlowRate.isActive = false

            // TODO : Will be addressed in sub-task DEN-6686.
            // _arterialPressureLimits.isLowActive = false
            // _arterialPressureLimits.isHighActive = false
            // _venousPressureLimits.isLowActive = false
            // _venousPressureLimits.isHighActive = false

        }

        onFwValidationSuccess: {
            _bloodFlowRate                     .setValid    (true)
            _dialysateFlowRate                 .setValid    (true)
            _duration                          .setValid    (true)
            _heparinDispensingRate             .setValid    (true)

            _heparinBolusVolume                .setValid    (true)
            _heparinStopTime                   .setValid    (true)

            _salineBolus                       .setValid    (true)
            //_acidConcentrate                   .setValid    (true)
            // _bicarbonateConcentrate            .setValid    (true)
            // _dialyzerType                      .setValid    (true)
            //
            // _dialysateTemperature              .setValid    (true)
            // _bloodPressureMeasurementInterval  .setValid    (true)
            // _rinsebackFlowRate                 .setValid    (true)

            // TODO : Will be addressed in sub-task DEN-6686.
            // _arterialPressureLimits            .setLowValid (true)
            // _arterialPressureLimits            .setHighValid(true)
            // _venousPressureLimits              .setLowValid (true)
            // _venousPressureLimits              .setHighValid(true)
        }

        onFwValidationFailed: {
        }

        onBloodFlowRate_ValidationFailed: {
            _bloodFlowRate.setValid(false)
        }

        onDialysateFlowRate_ValidationFailed: {
            _dialysateFlowRate.setValid(false)
        }

        onDuration_ValidationFailed: {
            _duration.setValid(false)
        }

        onHeparinDispensingRate_ValidationFailed: {
            _heparinDispensingRate.setValid(false)
        }

        onHeparinBolusVolume_ValidationFailed: {
            _heparinBolusVolume.setValid(false)
        }

        onHeparinStopTime_ValidationFailed: {
            _heparinStopTime.setValid(false)
        }

        onSalineBolusVolume_ValidationFailed: {
            _salineBolus.setValid(false)
        }

        onAcidConcentrate_ValidationFailed: {
            _acidConcentrate.setValid(false)
        }

        onBicarbonateConcentrate_ValidationFailed: {
            _bicarbonateConcentrate.setValid(false)
        }

        onDialyzerType_ValidationFailed: {
            _dialyzerType.setValid(false)
        }

        onDialysateTemp_ValidationFailed: {
            _dialysateTemperature.setValid(false)
        }

        onArterialPressureLimitLow_ValidationFailed: {
            _arterialPressureLimits.setLowValid(false)
        }

        onArterialPressureLimitHigh_ValidationFailed: {
            _arterialPressureLimits.setHighValid(false)
        }

        onVenousPressureLimitLow_ValidationFailed: {
            _venousPressureLimits.setLowValid(false)
        }

        onVenousPressureLimitHigh_ValidationFailed: {
            _venousPressureLimits.setHighValid(false)
        }

        onBloodPressureMeasureInterval_ValidationFailed: {
            _bloodPressureMeasurementInterval.setValid(false)
        }

        onRinsebackFlowRate_ValidationFailed: {
            _rinsebackFlowRate.setValid(false)
        }

        onScrollToParameter: {
            let prefix = "data."
            let contentYMargin = 80
            let newContentY = 0

            if (parameter === prefix+"bloodFlowRate") {
                newContentY = _bloodFlowRate.mapToItem(_bloodFlowRate.parent, 0, 0).y
            }
            else if (parameter === prefix+"dialysateFlowRate") {
                newContentY = _dialysateFlowRate.mapToItem(_dialysateFlowRate.parent, 0, 0).y
            }
            else if (parameter === prefix+"duration") {
                newContentY = _duration.mapToItem(_duration.parent, 0, 0).y
            }
            else if (parameter === prefix+"heparinDispensingRate") {
                newContentY = _heparinDispensingRate.mapToItem(_heparinDispensingRate.parent, 0, 0).y
            }
            else if (parameter === prefix+"heparinBolusVolume") {
                newContentY = _heparinBolusVolume.mapToItem(_heparinBolusVolume.parent, 0, 0).y
            }
            else if (parameter === prefix+"heparinStopTime") {
                newContentY = _heparinStopTime.mapToItem(_heparinStopTime.parent, 0, 0).y
            }
            else if (parameter === prefix+"salineBolus") {
                newContentY = _salineBolus.mapToItem(_salineBolus.parent, 0, 0).y
            }
            else if (parameter === prefix+"acidConcentrate") {
                newContentY = _acidConcentrate.mapToItem(_acidConcentrate.parent, 0, 0).y
            }
            else if (parameter === prefix+"bicarbonateConcentrate") {
                newContentY = _bicarbonateConcentrate.mapToItem(_bicarbonateConcentrate.parent, 0, 0).y
            }
            else if (parameter === prefix+"dialyzerType") {
                newContentY = _dialyzerType.mapToItem(_dialyzerType.parent, 0, 0).y
            }
            else if (parameter === prefix+"dialysateTemp") {
                newContentY = _dialysateTemperature.mapToItem(_dialysateTemperature.parent, 0, 0).y
            }
            else if (parameter === prefix+"arterialPressureLimitLow" ||
                     parameter === prefix+"arterialPressureLimitHigh") {
                newContentY = _arterialPressureLimits.mapToItem(_arterialPressureLimits.parent, 0, 0).y
            }
            else if (parameter === prefix+"venousPressureLimitLow" ||
                     parameter === prefix+"venousPressureLimitHigh") {
                newContentY = _venousPressureLimits.mapToItem(_venousPressureLimits.parent, 0, 0).y
            }
            else if (parameter === prefix+"bloodPressureMeasureInterval") {
                newContentY = _bloodPressureMeasurementInterval.mapToItem(_bloodPressureMeasurementInterval.parent, 0, 0).y
            }
            else if (parameter === prefix+"rinsebackFlowRate") {
                newContentY = _rinsebackFlowRate.mapToItem(_rinsebackFlowRate.parent, 0, 0).y
            }
            else {
                return
            }
            _flickable.contentY = newContentY - contentYMargin
        }
    }
}
