/*!
 *
 * Copyright (c) 2021-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    DiagnosticsDialog.qml
 * \author  (last)      Behrouz NematiPour
 * \date    (last)      04-Apr-2023
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  11-May-2021
 *
 */

// Qt
import QtQuick 2.12

// Project
import Gui.Actions      0.1
import Gui.VEventSpy    0.1

//  Qml imports
import "qrc:/globals"
import "qrc:/components"

/*!
 * \brief   Diagnostics is the screen
 */
ModalDialog { id: _root

    width   : Variables.applicationWidth
    height  : Variables.applicationHeight   - 60

    function col(idx, gap = 0) {
        return idx * 155 + gap
    }

    function row(idx, gap = 10) {
        return idx * 100 + gap
    }

    Rectangle {
        anchors.centerIn: _closeButton
        border.color    : Colors.white
        color           : Colors.transparent
        border.width    : Variables.borderWidth
        width           : _closeButton.width + 10
        height          : width
        radius          : width
    }

    CloseButton { id    : _closeButton
        anchors.left    : undefined
        anchors.right   : parent.right
        anchors.top     : undefined
        anchors.bottom  : parent.bottom
        anchors.margins : 10
        onClicked       : close()
    }

    DebugDataColumn { id: _DGROPumpColumn
        textObjectName  :"_DGROPumpData"
        title           : qsTr(" ROP ")
        x: col(0)
        y: row(0)
        model: [
            vDGROPump.pressure .toFixed(2) ,
            vDGROPump.flowRate .toFixed(2) ,
            vDGROPump.pwm      .toFixed(2) ,
            vDGROPump.state
        ]
        label: [
            "MaxPrs",
            "Flow"  ,
            "PWM"   ,
            "stt"   ,
        ]
    }

    DebugDataColumn { id: _DGDrainPumpColumn
        textObjectName  :"_DGDrainPumpData"
        title           : qsTr(" DRP ")
        x: col(1)
        y: row(0)
        model: [
            vDGDrainPump.rpmi                       ,
            vDGDrainPump.dac                        ,
            vDGDrainPump.state                      ,
            vDGDrainPump.rpmo                       ,
            vDGDrainPump.targetFLPMO    .toFixed(2) ,
            vDGDrainPump.currentA       .toFixed(2) ,
            vDGDrainPump.direction                  ,
        ]
        label: [
            "TgtSpd",
            "DAC"   ,
            "stt"   ,
            "Spd"   ,
            "tgt"   ,
            "cur"   ,
            "dir"   ,
        ]
    }

    DebugDataColumn { id: _DGPressuresColumn
        textObjectName  :"_DGPressuresData"
        title           : qsTr(" Prssr ")
        x: col(2)
        y: row(0)
        model: [
            vDGPressures.roInletPSI     .toFixed(2) ,
            vDGPressures.roOutletPSI    .toFixed(2) ,
            vDGPressures.drainInletPSI  .toFixed(2) ,
            vDGPressures.drainOutletPSI .toFixed(2) ,
            vDGPressures.barometricPSI  .toFixed(2) ,
        ]
        label: [
            "PPi",
            "PPo",
            "PRd",
            "PDr",
            "bar",
        ]
    }

    DebugDataColumn { id: _DGReservoirColumn
        textObjectName  :"_DGReservoirData"
        title           : qsTr(" Rsrvr ")
        x: col(3)
        y: row(0)
        model: [
            vDGReservoir.activeReservoir            ,
            vDGReservoir.fillToVol                  ,
            vDGReservoir.drainToVol                 ,
        ]
        label: [
            "Act",
            "Fil",
            "Drn",
        ]
    }

    DebugDataColumn { id: _DGHeatersColumn
        textObjectName  :"_DGHeatersData"
        title           : qsTr(" Heatrs ")
        x: col(4)
        y: row(0)
        model: [
            vDGHeaters.mainPrimayHeaterDC       .toFixed(2),
            vDGHeaters.smallPrimaryHeaterDC     .toFixed(2),
            vDGHeaters.trimmerHeaterDC          .toFixed(2),
        ]
        label: [
            "HP1",
            "HP2",
            "HR" ,
        ]
    }

    Text { id : _mouseEventCountText
        text: String("Touch: %1,%2").arg(GuiEventSpy.touchCount   /*.toString().padStart(4,'0')*/ )
                                    .arg(GuiEventSpy.touchPoints  /*.toString().padStart(4,'0')*/ )
        x: col(3.5)
        y: row(1.5)
        visible: true
        horizontalAlignment: Text.AlignLeft
        color: Colors.textMain
        font.pixelSize: Fonts.fontPixelDebugText
        MouseArea {
            anchors.fill: _mouseEventCountText
            onClicked: GuiEventSpy.doTouchReset()
        }
    }

    Text { id : _canbusFaultCountText
        property int count: 0
        text: qsTr("CANerr: %1").arg(count)
        x: col(5.0)
        y: row(1.5)
        visible: true
        horizontalAlignment: Text.AlignLeft
        color: Colors.textMain
        font.pixelSize: Fonts.fontPixelDebugText
    }

    DebugDataColumn { id: _DGLoadCellReadingsColumn
        textObjectName  :"_DGLoadCellReadingsData"
        title           : qsTr(" LoadCl ")
        x: col(5)
        y: row(0)
        model: [
            vDGLoadCellReadings.reservoir1Prim .toFixed(2) ,
            vDGLoadCellReadings.reservoir1Bkup .toFixed(2) ,
            vDGLoadCellReadings.reservoir2Prim .toFixed(2) ,
            vDGLoadCellReadings.reservoir2Bkup .toFixed(2) ,
        ]
        label: [
            "A1",
            "A2",
            "B1",
            "B2",
        ]
    }

    DebugDataColumn { id: _DGTemperaturesColumn
        textObjectName  :"_DGTemperaturesData"
        title           : qsTr(" Tmprtr ")
        x: col(6)
        y: row(0)
        model: [
            vDGTemperatures.inletPrimaryHeater          .toFixed(2) ,
            vDGTemperatures.heatDisinfect               .toFixed(2) ,
            vDGTemperatures.outletPrimaryHeater         .toFixed(2) ,
            vDGTemperatures.conductivitySensor1         .toFixed(2) ,
            vDGTemperatures.conductivitySensor2         .toFixed(2) ,
            vDGTemperatures.outletRedundancy            .toFixed(2) ,
            vDGTemperatures.inletDialysate              .toFixed(2) ,
            vDGTemperatures.primaryHeaterThermoCouple   .toFixed(2) ,
            vDGTemperatures.trimmerHeaterThermoCouple   .toFixed(2) ,
            vDGTemperatures.primaryHeaterColdJunction   .toFixed(2) ,
            vDGTemperatures.trimmerHeaterColdJunction   .toFixed(2) ,
            vDGTemperatures.primaryHeaterInternal       .toFixed(2) ,
            vDGTemperatures.trimmerHeaterInternal       .toFixed(2) ,
            vDGTemperatures.fpgaBoard                   .toFixed(2) ,
            vDGTemperatures.loadCellA1B1                .toFixed(2) ,
            vDGTemperatures.loadCellA2B2                .toFixed(2) ,
            vDGTemperatures.internalTHDORTD             .toFixed(2) ,
            vDGTemperatures.internalTDIRTD              .toFixed(2) ,
            vDGTemperatures.interalTHDRTD               .toFixed(2) ,
            vDGTemperatures.internalCondSnsrTemp        .toFixed(2) ,
            vDGTemperatures.baroTempSensor              .toFixed(2) ,
        ]
        label: [
            "TPi"   ,
            "THd"   ,
            "TPo"   ,
            "TD1"   ,
            "TD2"   ,
            "TRo"   ,
            "TDi"   ,
            "HP.Trm",
            "HR.Trm",
            "HP.Cld",
            "HR.Cld",
            "HP.Int",
            "HR.Int",
            "fpga"  ,
            "cell11",
            "cell22",
            "iTHDO" ,
            "iTDI"  ,
            "iTHD"  ,
            "iCond" ,
            "baro"  ,
        ]
    }

    DebugDataColumn { id: _DGConductivityColumn
        textObjectName  :"_DGConductivityData"
        title           : qsTr(" Conduct ")
        x: col(3.7)
        y: row(3.2)
        model: [
            vDGConductivity.RORejectionRatio    .toFixed(3),
            vDGConductivity.CPi                 .toFixed(1),
            vDGConductivity.CPo                 .toFixed(1),
            vDGConductivity.CD1                 .toFixed(1),
            vDGConductivity.CD2                 .toFixed(1),
            vDGConductivity.CPiRaw              .toFixed(1),
            vDGConductivity.CPoRaw              .toFixed(1),
            vDGConductivity.CD1Raw              .toFixed(1),
            vDGConductivity.CD2Raw              .toFixed(1),
            vDGConductivity.CPiSensorStatus     .toFixed(1),
            vDGConductivity.CPoSensorStatus     .toFixed(1),
            vDGConductivity.CD1SensorStatus     .toFixed(1),
            vDGConductivity.CD2SensorStatus     .toFixed(1),
        ]
        label: [
            "ROrr" ,
            "CPi"  ,
            "CPo"  ,
            "CD1"  ,
            "CD2"  ,
            "CPir" ,
            "CPor" ,
            "CD1r" ,
            "CD2r" ,
            "CPis" ,
            "CPos" ,
            "CD1s" ,
            "CD2s" ,
        ]
    }

    DebugDataColumn { id: _HDAirColumn
        textObjectName  :"_HDAirData"
        title           : qsTr("Air Status")
        x: col(2.4)
        y: row(5.5)
        model: [
            vHDAirBubble    .venousAirBubbleStatus  ,
            vHDAirTrap      .airTrapLowerLevel      ,
            vHDAirTrap      .airTrapUpperLevel      ,
        ]
        label: [
            "ADV"   ,
            "ATll"  ,
            "ATul"  ,
        ]
    }

    DebugDataColumn { id: _DGOperationModeColumn
        textObjectName  :"_DGOperationModeData"
        title           : qsTr(" DG Mode ")
        x: col(2.5)
        y: row(1.9)
        model: [
            vDGOperationMode.text ,
        ]
        fontPixelSizeText: Fonts.fontPixelDebugTitle
    }

    // --- HD ---
    DebugDataColumn { id: _HDBloodFlowColumn
        textObjectName  :"_HDBloodFlowData"
        title           : qsTr(" BP ")
        x: col(0)
        y: row(2.5)
        model: [
            vTreatmentBloodFlow.bloodFlow_FlowSetPoint                 ,
            vTreatmentBloodFlow.bloodFlow_MeasuredFlow     .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_RotorSpeed       .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_MotorSpeed       .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_MotorCtlSpeed    .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_MotorCtlCurrent  .toFixed(2) ,
      "%" + vTreatmentBloodFlow.bloodFlow_PWMDutyCycle     .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_RotorCount       .toFixed(2) ,
            vTreatmentBloodFlow.bloodFlow_PresFlow         .toFixed(2) ,
        ]
        label: [
            "Tgt.Flow"  ,
            "Msr.Flow"  ,
            "Rot.Spd"   ,
            "Mot.Spd"   ,
            "MC.Spd"    ,
            "MC.Cur"    ,
            "PWM"       ,
            "Rtr.Cnt"   ,
            "Prs.Flow"  ,
        ]
    }

    DebugDataColumn { id: _HDDialysateInletFlowColumn
        textObjectName  :"_HDDialysateInletFlowData"
        title           : qsTr(" DPi ")
        x: col(1.2)
        y: row(2.5)
        model: [
            vTreatmentDialysateFlow.dialysateFlow_FlowSetPoint   .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_MeasuredFlow   .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_RotorSpeed     .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_MotorSpeed     .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_MotorCtlSpeed  .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_MotorCtlCurrent.toFixed(2) ,
      "%" + vTreatmentDialysateFlow.dialysateFlow_PWMDutyCycle   .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_RotorCount     .toFixed(2) ,
            vTreatmentDialysateFlow.dialysateFlow_PresFlow       .toFixed(2) ,
        ]
        label: [
            "Tgt.Flow"  ,
            "Msr.Flow"  ,
            "Rot.Spd"   ,
            "Mot.Spd"   ,
            "MC.Spd"    ,
            "MC.Cur"    ,
            "PWM"       ,
            "Rtr.Cnt"   ,
            "Prs.Flow"  ,
        ]
    }

    DebugDataColumn { id: _HDDialysateOutletFlowColumn
        textObjectName  :"_HDDialysateOutletFlowData"
        title           : qsTr(" UF/DPo ")
        x: col(2.4)
        y: row(2.5)
        model: [
            vTreatmentUltrafiltration.ultrafiltration_RefUFVol       .toFixed(3) ,
            vTreatmentUltrafiltration.ultrafiltration_MeasUFVol      .toFixed(3) ,
            vTreatmentUltrafiltration.ultrafiltration_RotorSpeed     .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_MotorSpeed     .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_MotorCtlSpeed  .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_MotorCtlCurrent.toFixed(2) ,
      "%" + vTreatmentUltrafiltration.ultrafiltration_PWMDtCycle     .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_DopCorrOffset  .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_DopCalcRate    .toFixed(2) ,
            vTreatmentUltrafiltration.ultrafiltration_UfCalcRate     .toFixed(2) ,
        ]
        label: [
            "UFRef"     ,
            "UFMeas"    ,
            "Rot.Spd"   ,
            "Mot.Spd"   ,
            "MC.Spd"    ,
            "MC.Cur"    ,
            "PWM"       ,
            "DopOfst"   ,
            "DopRate"   ,
            "UFcRate"   ,
        ]
    }

    DebugDataColumn { id: _HDPressureOcclusionColumn
        textObjectName  :"_HDPressureOcclusionData"
        title           : qsTr(" Prsr Oc ")
        x: col(3.7)
        y: row(1.9)
        model: [
            vTreatmentPressureOcclusion.arterialPressure             .toFixed(2) ,
            vTreatmentPressureOcclusion.venousPressure               .toFixed(2) ,
            vTreatmentPressureOcclusion.bloodPumpOcclusion                       ,
        ]
        label: [
            "PBA" ,
            "PBo" ,
            "OB"  ,
        ]
    }

    DebugDataColumn { id: _HDSyringePumpColumn
        textObjectName  :"_HDSyringePumpData"
        title           : qsTr(" Syringe ")
        x: col(4.6)
        y: row(1.9)
        model: [
            vHDSyringePump.syringePumpState                 ,
            vHDSyringePump.heparinState                     ,
            vHDSyringePump.setRate              .toFixed(2) ,
            vHDSyringePump.measuredRate         .toFixed(2) ,
            vHDSyringePump.syringePumpPosition              ,
            vHDSyringePump.volumeDelivered      .toFixed(2) ,
            vHDSyringePump.measuredHome         .toFixed(2) ,
            vHDSyringePump.measuredSwitch       .toFixed(2) ,
            vHDSyringePump.measuredForce        .toFixed(2) ,
            vHDSyringePump.safetyVol            .toFixed(2) ,
            vHDSyringePump.status                           ,
        ]
        label: [
            "srng.St",
            "hprn.St",
            "setRate",
            "msrRate",
            "srngPos",
            "VolumeD",
            "Msr.Hom",
            "Msr.Swt",
            "Msr.Frc",
            "safe.Vl",
            "status" ,
        ]
    }

    DebugDataColumn { id: _HDOperationModeColumn
        textObjectName  :"_HDOperationModeData"
        title           : qsTr(" HD Mode ")
        x: col(0.5)
        y: row(1.9)
        model: [
            vHDOperationMode.text ,
        ]
        fontPixelSizeText: Fonts.fontPixelDebugTitle
    }

    DebugDataColumn { id: _DGValvesStatesColumn
        textObjectName  :"_DGValvesStatesData"
        title           : qsTr("Vlv")
        x: col(7.65) // pleae don't use 2 digits, this one is an exception
        y: row(0.0)
        width: 50
        model: [
            "%1,%2".arg(vDGValvesStates.valveStatus_VRF).arg(vDGValvesStates.valveStates_VRF),
            "%1,%2".arg(vDGValvesStates.valveStatus_VRI).arg(vDGValvesStates.valveStates_VRI),
            "%1,%2".arg(vDGValvesStates.valveStatus_RES).arg(vDGValvesStates.valveStates_RES),
            "%1,%2".arg(vDGValvesStates.valveStatus_VRO).arg(vDGValvesStates.valveStates_VRO),
            "%1,%2".arg(vDGValvesStates.valveStatus_VPO).arg(vDGValvesStates.valveStates_VPO),
            "%1,%2".arg(vDGValvesStates.valveStatus_VBF).arg(vDGValvesStates.valveStates_VBF),
            "%1,%2".arg(vDGValvesStates.valveStatus_VRC).arg(vDGValvesStates.valveStates_VRC),
            "%1,%2".arg(vDGValvesStates.valveStatus_VDR).arg(vDGValvesStates.valveStates_VDR),
            "%1,%2".arg(vDGValvesStates.valveStatus_VPI).arg(vDGValvesStates.valveStates_VPI),
            "%1,%2".arg(vDGValvesStates.valveStatus_VSP).arg(vDGValvesStates.valveStates_VSP),
            "%1,%2".arg(vDGValvesStates.valveStatus_VR1).arg(vDGValvesStates.valveStates_VR1),
            "%1,%2".arg(vDGValvesStates.valveStatus_VR2).arg(vDGValvesStates.valveStates_VR2),
            "%1,%2".arg(vDGValvesStates.valveStatus_VPD).arg(vDGValvesStates.valveStates_VPD),
        ]
        label: [
            "VRF",
            "VRI",
            "RES",
            "VRO",
            "VPO",
            "VBF",
            "VRC",
            "VDR",
            "VPI",
            "VSP",
            "VR1",
            "VR2",
            "VPD",
        ]
    }

    DebugDataColumn { id: _HDBloodLeakColumn
        textObjectName  :"_HDBloodLeakData"
        title           : qsTr(" BLD ")
        x: col(7)
        y: row(4.5)
        model: [
            vHDBloodLeak.bloodLeakStatus      ,
            vHDBloodLeak.bloodLeakState       ,
        ]
        label: [
            "Stats" ,
            "State" ,
        ]
    }

    DebugDataColumn { id: _HDAlarmTopColumn
        textObjectName  :"_HDAlarmTopData"
        title           : qsTr(" Alarms ")
        x: col(5)
        y: row(5.5)
        model: [
            _alarmItem.alarm_AlarmID ,
        ]
        label: [
            "Top" ,
        ]
    }

    // TODO: The TouchRect should be unnecessary since the first communication message with UI/HD is the version.
    TouchRect {
        x           : col(5.0)
        y           : row(6.4)
        width       : 425
        height      : 80
        onClicked   : vAdjustmentVersions.doAdjustment()
        radius      : 10
        Column {
            anchors.top : parent.top
            anchors.topMargin: -20
            anchors.left: parent.left
            anchors.leftMargin: 5

            spacing: -30
            DebugDataColumn { id: _HDVersionsColumn
                textObjectName  :"_HDVersionsData"
                title           : ""
                horizontalAlignmentText: Text.AlignLeft
                fontPixelSizeText: Fonts.fontPixelDebugTitle
                model: [ "HD: v%1.%2.%3-%4 v%5.%6.%7-%8 c%9"
                    .arg(vAdjustmentVersions.hdVerMajor             )
                    .arg(vAdjustmentVersions.hdVerMinor             )
                    .arg(vAdjustmentVersions.hdVerMicro             )
                    .arg(vAdjustmentVersions.hdVerBuild             )
                    .arg(vAdjustmentVersions.hdVerFPGAMajor         )
                    .arg(vAdjustmentVersions.hdVerFPGAMinor         )
                    .arg(vAdjustmentVersions.hdVerFPGALab           )
                    .arg(vAdjustmentVersions.hdVerFPGAId            )
                    .arg(vAdjustmentVersions.hdVerCompatibilityRev  )
                ]
            }

            DebugDataColumn { id: _DGVersionsColumn
                textObjectName  :"_DGVersionsData"
                title           : ""
                horizontalAlignmentText: Text.AlignLeft
                fontPixelSizeText: Fonts.fontPixelDebugTitle
                model: [ "DG: v%1.%2.%3-%4 v%5.%6.%7-%8 c%9"
                    .arg(vAdjustmentVersions.dgVerMajor             )
                    .arg(vAdjustmentVersions.dgVerMinor             )
                    .arg(vAdjustmentVersions.dgVerMicro             )
                    .arg(vAdjustmentVersions.dgVerBuild             )
                    .arg(vAdjustmentVersions.dgVerFPGAMajor         )
                    .arg(vAdjustmentVersions.dgVerFPGAMinor         )
                    .arg(vAdjustmentVersions.dgVerFPGALab           )
                    .arg(vAdjustmentVersions.dgVerFPGAId            )
                    .arg(vAdjustmentVersions.dgVerCompatibilityRev  )
                ]
            }
        }
    }

    DebugDataColumn { id: _PreTreatmentStatesColumn
        textObjectName  :"_PreTreatmentStatesData"
        title           : qsTr(" PreTx States ")
        x: col(1.5)
        y: row(5.5)
        model: [ "%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11"
            .arg(vPreTreatmentStates.subMode                 )
            .arg(vPreTreatmentStates.waterSampleState        )
            .arg(vPreTreatmentStates.selfTestConsumablesState)
            .arg(vPreTreatmentStates.selfTestNoCartridgeState)
            .arg(vPreTreatmentStates.installationState       )
            .arg(vPreTreatmentStates.selfTestDryState        )
            .arg(vPreTreatmentStates.primeState              )
            .arg(vPreTreatmentStates.recirculateState        )
            .arg(vPreTreatmentStates.patientConnectionState  )
            .arg(vPreTreatmentStates.wetSelfTestsState       )
            .arg(vPreTreatmentStates.preTreatmentRsrvrState  )
        ]
    }

    Text { id : _hdResetInformation
        x: col(0.2)
        y: row(6.4)
        visible: true
        text: "HDrst:" + vGeneralEvent.hdReset
        horizontalAlignment: Text.AlignLeft
        color: Colors.textMain
        font.pixelSize: Fonts.fontPixelDebugText
    }

    Text { id : _dgResetInformation
        x: col(0.2)
        y: row(6.8)
        visible: true
        text: "DGrst:" + vGeneralEvent.dgReset
        horizontalAlignment: Text.AlignLeft
        color: Colors.textMain
        font.pixelSize: Fonts.fontPixelDebugText
    }

    Connections { target: _GuiView
        function onDidActionReceive( vAction, vData ) {
            // DEBUG: console.debug("onDidActionReceive", vAction, vData)
            if (vAction === GuiActions.ID_CANBusFaultCount ) {
                _canbusFaultCountText.count = vData[0]
            }
        }
    }
}

