/*!
 *
 * Copyright (c) 2020-2025 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    NumPad.qml
 * \author  (last)      Nico Ramirez
 * \date    (last)      28-Aug-2025
 * \author  (original)  Nico Ramirez
 * \date    (original)  28-Aug-2025
 *
 */

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtGraphicalEffects 1.12

import "qrc:/components"
import "qrc:/globals"

Rectangle { id: _root
    property var settingValue           : undefined
    property alias unit                 : _unitText.text
    property alias range                : _range.text
    property alias title                : _title.text

    property alias displayValue         : _valueLabel.text
    property int precision              : 0
    property var getter                 : null
    property var setter                 : null
    property var validator              : null
    readonly property bool isValueValid : validator ? validator(valueInt) : true
    readonly property var valueInt      : isNaN(parseInt(_valueLabel.text)) ? undefined : parseInt(_valueLabel.text)
    readonly property string backSpace  : "qrc:/images/iBackspace"
    property bool isOpened              : false

    width                   : Variables.numPadWidth
    height                  : Variables.numPadHeight
    visible                 : false
    radius                  : 9
    color                   : Colors.backgroundMain
    x                       : Math.round((Variables.applicationWidth   - _root.width) / 2)
    y                       : Math.round((Variables.applicationHeight  - _root.height) / 2)
    onVisibleChanged        : if ( ! _root.visible  )   { reset()                           }
    onDisplayValueChanged   : if ( _root.setter     )   { _root.setter( _valueLabel.text )  }
    onSettingValueChanged   : _valueLabel.text = _root.settingValue !== undefined ? _root.settingValue : ""

    signal cancel()

    // slide animation
    Behavior on x { NumberAnimation { duration: Variables.keybardAnimationDuration } }

    function open(entry, title, min, max, unit) {
        reset()
        _root.settingValue  = Qt.binding(function () { return entry.text })
        _root.title         = title
        _root.unit          = unit
        _root.range         = min.isEmpty &&
                              max.isEmpty ? "" : ("%1 %2 - %3") .arg(qsTr("Range:"))
                                                                .arg(min)
                                                                .arg(max)
        _root.getter        = entry.text
        _root.setter        = function (value) { entry.text  = value }
        _root.validator     = function (value) { { return value >= min && value <= max } }
        _keyboard.setVisible(false)
        show()
    }

    function show() {
        if ( ! _root.visible  ) { _root.visible = true  }
        if ( ! isOpened ) {
            x = x + _root.width
            isOpened = true
        }
    }

    function hide( hideOnly = false ) {
        if ( isOpened ) {
            x = x - _root.width
            isOpened = false
        }
        else if ( _root.visible && ! hideOnly )   { _root.visible = false }
    }

    function reset() {
        _numPadGrid.replaceValueText = true
        _root.getter = null
        _root.setter = null
        _root.displayValue = ""
    }

    TouchRect { id  : _sliderButton
        anchors {
            verticalCenter          : parent.verticalCenter
            horizontalCenter        : _root.isOpened ? parent.left : parent.right
            horizontalCenterOffset  : _root.isOpened ? 10 * -1 : 0
        }
        z               : -1
        height          : 80
        width           : height
        radius          : height
        border.color    : Colors.transparent
        backgroundColor : Colors.backgroundButtonSelect
        onPressed       : isOpened ? hide() : show()

        Image { id  : _iconImage
            anchors {
                verticalCenter          :  parent.verticalCenter
                horizontalCenter        :  parent.horizontalCenter
                horizontalCenterOffset  : _root.isOpened ? 15 * -1 : 15
            }
            height  : 35
            width   : 35
            fillMode: Image.PreserveAspectFit
            source  : isOpened ? "qrc:/images/iChevronLeft" :
                                 "qrc:/images/iChevronRight"
        }
    }

    Text { id: _title
        anchors {
            top             : _root.top
            topMargin       : Variables.defaultMargin * 2.5
            horizontalCenter: _root.horizontalCenter
        }
        font {
            pixelSize   : Fonts.fontPixelSection
            weight      : Font.Medium
        }
        color   : "white"
    }

    Text { id: _range
        anchors {
            top             : _title.bottom
            topMargin       : Variables.defaultMargin
            horizontalCenter: parent.horizontalCenter
        }
        font {
            pixelSize   : 22
            weight      : Font.Medium
        }
        color           : "#E0CDA9"
    }

    Rectangle { id: _numRect
        anchors {
            top             : _range.bottom
            topMargin       : Variables.defaultMargin
            horizontalCenter: _root.horizontalCenter
        }
        width   : _root.width * 0.70
        height  : 90
        radius  : 10
        color   : "#324867"

        Text { id: _valueLabel
            anchors.centerIn: parent
            font {
                pixelSize   : 65
                weight      : Font.DemiBold
            }
            color   : isValueValid ? "white" : "gray"
            text    : ""
        }
    }

    Rectangle {
        anchors {
            top         : _root.top
            bottom      : _root.bottom
            right       : _root.left
            rightMargin : -10
        }
        width   : 20
        color   : _root.color
    }

    Text { id: _unitText
        anchors {
            horizontalCenter: parent.horizontalCenter
            top             :  _numRect.bottom
            topMargin       : 5
        }
        font.pixelSize  : 20
        color           : "white"
    }

    Grid { id: _numPadGrid
        anchors {
            left    : _root.left
            right   : _root.right
            bottom  : _root.bottom
            margins : Variables.defaultMargin * 2
        }
        columns         : 3
        columnSpacing   : 2
        rows            : 4
        rowSpacing      : 2
        height          : _root.height * 0.50

        property bool   replaceValueText: true
        property int    cellWidth       : _numPadGrid.width  / columns
        property int    cellHeight      : _numPadGrid.height / rows

        Repeater {
            model: [ "7", "8", "9",
                     "4", "5", "6",
                     "1", "2", "3",
                     ".", "0", backSpace ]

            delegate: Button { id: _keyButton
                width               : _numPadGrid.cellWidth
                height              : _numPadGrid.cellHeight
                text                : modelData === backSpace ? "" : modelData
                icon.source         : modelData === backSpace ? modelData : ""
                icon.height         : 45
                icon.width          : 45
                enabled             : modelData === "." ? precision > 0 : true

                contentItem: Rectangle {
                    anchors.fill    : parent
                    color           : _keyButton.pressed ?  Colors.backgroundButtonSelectDark :
                                                            modelData === backSpace ? Qt.darker ("#263B57", 1.05) :
                                                                                     "#263B57"
                    Image {
                        anchors.centerIn: parent
                        source          : _keyButton.icon.source
                        width           : _keyButton.icon.width
                        height          : _keyButton.icon.height
                        fillMode        : Image.PreserveAspectFit
                    }
                    Text {
                        anchors.centerIn: parent
                        text            : _keyButton.text
                        font.pixelSize  : 40
                        color           : enabled ? "white" : "dimgrey"
                    }
                }
                
                onPressed: {
                    if (modelData === backSpace ) {
                        _numPadGrid.replaceValueText = false
                        _valueLabel.text = _valueLabel.text.substr(0, _valueLabel.text.length - 1)
                    }
                    else {
                        if (_numPadGrid.replaceValueText) {
                            _valueLabel.text = _keyButton.text
                            _numPadGrid.replaceValueText = false
                        }
                        else if (_valueLabel.text.length < 3) {
                            _valueLabel.text += _keyButton.text
                        }
                    }
                }
            }
        }
    }
}
