// Qt
import QtQuick 2.15

// Project

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

ModalDialog { id: _root
    property int index              : -1
    property int sensorIndex        : -1
    property string titleText       : ""
    property string componentName   : ""
    property var entries            : []
    property var rejections         : vCalibrationSettings.rejectionReasons
    property var entryNames         : vCalibrationSettings.columnTitle
    property var model              : null
    property alias  numPad          : _numPad

    height  : Variables.smallDialogHeight
    width   : Variables.smallDialogWidth
    y       : Math.round((Variables.applicationHeight - height) / 2) - Variables.headerHeight
    x       : Math.round((Variables.applicationWidth - width) / 2) - 200
    radius  : Variables.adjustmentDialogRadius

    backgroundItem  : [ NumPad  { id: _numPad
        x               : _root.width
        y               : 0
        isOpened        : true
        allowDecimal    : true
        showSliderButton: false
        showRange       : false
        numCharacters   : 6
        isFloat         : true
    } ]

    onOpened: {
        Qt.callLater(function() {
            if (_repeater.count > 0) {
                _repeater.itemAt(0).textEntry.clicked(0)
            }
        })
    }

    onClosed: {
        _root.entries = []
    }

    function confirmClicked() {
        let payload = []
        for (let i = 0; i < _repeater.count; ++i) {
            payload[i] = _repeater.itemAt(i).textEntry.text
        }
        vCalibrationSettings.doAdjustment(_root.index,
                                          _root.sensorIndex,
                                          payload)

        // REMOVE LATER TO THE ACCEPT OF THE RESPONSE MESSAGE *****
        close()
    }

    function confirmEnabled() {
        for (let i = 0; i < _repeater.count - 1; ++i) {
            const item = _repeater.itemAt(i)
            if (!item || !item.textEntry.textInput.acceptableInput) return false
        }

        return true
    }

    function openDialog (vIndex, vSensorIndex, vRecord){
        _root.model           = vRecord
        _root.index           = vIndex
        _root.sensorIndex     = vSensorIndex
        _root.titleText       = vRecord.title
        _root.componentName   = vRecord.component
        _root.entries         = vRecord.payload
        open()
    }

    header: Item { id : _headerRect
        implicitHeight: Variables.alarmDialogHeaderHeight

        TitleText { id : _titleText
            text: qsTr("Edit %1").arg(titleText)
            font {
                pixelSize   : Fonts.fontPixelSection
                weight      : Font.Medium
            }
            color   : Colors.offWhite
            width   : _root.width - Variables.defaultMargin * 2
            height  : parent.height / 2
            anchors {
                bottom              : parent.bottom
                horizontalCenter    : parent.horizontalCenter
                margins             : Variables.defaultMargin * 2
            }
        }

        Text {
            visible: _root.componentName !== ""

            text    : ("(%1)").arg(componentName)
            color   : Colors.offWhite
            font {
                pixelSize   : Fonts.fontPixelTextRectTitle
            }
            anchors {
                top             : _titleText.bottom
                horizontalCenter: parent.horizontalCenter
            }
        }

        CloseButton { id : _closeButton
            anchors {
                right           : parent.right
                top             : parent.top
                margins         : Variables.adjustmentButtonMargin
            }

            onClicked : {
                close()
            }
        }
    }

    Grid { id: entryColumn
        anchors.horizontalCenter: parent.horizontalCenter
        columns         : 2
        rowSpacing      : Variables.defaultMargin * 5
        columnSpacing   : Variables.defaultMargin * 5

        Repeater { id: _repeater
            model: _root.entries

            delegate: Item { id: _delegate
                readonly property bool isCalTime: index === _repeater.count - 1
                property alias textEntry        : _textEntry

                height          : Variables.contentHeight
                width           : Variables.treatmentFlowsComponentWidth

                Text { id           : _label
                    anchors {
                        top             : parent.top
                        horizontalCenter: parent.horizontalCenter
                    }

                    height          : Variables.contentHeight
                    width           : parent.width

                    color           : Colors.textMain
                    font.pixelSize  : Fonts.fontPixelTextRectExtra
                    font.weight     : Font.Medium
                    text            : _root.entryNames[index] ?? ""
                    horizontalAlignment: Text.AlignHCenter
                }

                Rectangle { id: _rect
                    anchors {
                        top             : _label.bottom
                        horizontalCenter: parent.horizontalCenter

                    }
                    height  : 75
                    width   : parent.width
                    radius  : 8.5
                    color   : isCalTime ? Colors.transparent : Colors.panelBackgroundColor

                    border {
                        width   : isCalTime ? 0 : 2
                        color   : _root.rejections[index] === Variables.noRejectReason ?    _root.entryNames[index] === _root.numPad.title ?    Colors.borderButton :
                                                                                                                                                Colors.panelBorderColor :
                                                                                                                                                Colors.red
                    }

                    TextEntry { id : _textEntry
                        anchors.centerIn        : parent
                        text                    : Number(modelData).toFixed(3) ?? Variables.emptyEntry
                        textInput.font.pixelSize: Fonts.fontPixelValueControl
                        line.visible            : false
                        textInput.color         :  _textEntry.textInput.acceptableInput ? Colors.offWhite : Colors.red
                        useQtNumPad             : false
                        showPlaceHolderText     : true
                        visible                 : ! isCalTime

                        validator: DoubleValidator {
                            bottom  : numPad.validatorMin
                            top     : numPad.validatorMax
                            decimals: 3
                        }

                        onClicked: _root.numPad.open(   _textEntry,
                                                        _root.entryNames[index],
                                                        _root.numPad.validatorMin,
                                                        _root.numPad.validatorMax,
                                                        "")
                    }

                    Text { id : _textEntryCalTime
                        anchors.centerIn        : parent
                        text                    : modelData ?? Variables.emptyEntry
                        font.pixelSize          : Fonts.fontPixelTextRectExtra
                        color                   : Colors.offWhite
                        visible                 : isCalTime
                    }
                }
            }
        }
    }

    ConfirmButton { id : _confirmButton
        width       : Variables.defaultButtonWidth
        height      : Variables.defaultButtonHeight
        enabled     : _root.confirmEnabled()
        anchors {
            top             : undefined
            right           : undefined
            margins         : 0
            bottom          : _root.contentItem.bottom
            bottomMargin    : Variables.defaultMargin * 2
            horizontalCenter: _root.contentItem.horizontalCenter
        }
        onClicked   : _root.confirmClicked()
    }
}

