// SPDX-License-Identifier: GPL-3.0-or-later

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright (C) 2013 - 2024, nymea GmbH
* Copyright (C) 2024 - 2025, chargebyte austria GmbH
*
* This file is part of nymea-app.
*
* nymea-app is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nymea-app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with nymea-app. If not, see <https://www.gnu.org/licenses/>.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

import QtQuick 2.8
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.2
import "../components"
import "../delegates"
import Nymea 1.0

Page {
    id: root
    // Needs to be set and filled in with thingId and eventTypeId
    property StateDescriptor stateDescriptor: null

    readonly property Thing thing: stateDescriptor && stateDescriptor.thingId ? engine.thingManager.things.getThing(stateDescriptor.thingId) : null
    readonly property Interface iface: stateDescriptor && stateDescriptor.interfaceName ? Interfaces.findByName(stateDescriptor.interfaceName) : null
    readonly property StateType stateType: thing ? thing.thingClass.stateTypes.getStateType(stateDescriptor.stateTypeId)
                                              : iface ? iface.stateTypes.findByName(stateDescriptor.interfaceState) : null

    signal backPressed();
    signal completed();

    header: NymeaHeader {
        text: qsTr("Condition")
        onBackPressed: root.backPressed();
    }

    GroupBox {
        anchors {
            left: parent.left
            top: parent.top
            right: parent.right
            margins: Style.margins
        }

        GridLayout {
            anchors.fill: parent
            columns: width > 600 ? 2 : 1

            Label {
                Layout.fillWidth: true
                text: "%1, %2".arg(root.thing.name).arg(root.stateType.displayName)
            }

            ComboBox {
                id: operatorComboBox
                Layout.fillWidth: true
                property bool isNumeric: {
                    switch (root.stateType.type.toLowerCase()) {
                    case "bool":
                    case "string":
                    case "qstring":
                    case "color":
                        return false;
                    case "int":
                    case "double":
                        return true;
                    }
                    console.warn("ParamDescriptorDelegate: Unhandled data type:", root.stateType.type.toLowerCase());
                    return false;
                }

                model: isNumeric ?
                           numericModel
                         : nonNumericModel

                textRole: "text"

                ListModel {
                    id: numericModel
                    ListElement { text: qsTr("is equal to"); value: ParamDescriptor.ValueOperatorEquals }
                    ListElement { text: qsTr("is not equal to"); value: ParamDescriptor.ValueOperatorNotEquals }
                    ListElement { text: qsTr("is greater than"); value: ParamDescriptor.ValueOperatorGreater }
                    ListElement { text: qsTr("is less than"); value: ParamDescriptor.ValueOperatorLess }
                    ListElement { text: qsTr("is greater than or equal to"); value: ParamDescriptor.ValueOperatorGreaterOrEqual }
                    ListElement { text: qsTr("is less than or equal to"); value: ParamDescriptor.ValueOperatorLessOrEqual }
                }

                ListModel {
                    id: nonNumericModel
                    ListElement { text: qsTr("is"); value: ParamDescriptor.ValueOperatorEquals }
                    ListElement { text: qsTr("is not "); value: ParamDescriptor.ValueOperatorNotEquals }
                }

            }

            GroupBox {
                Layout.columnSpan: parent.columns
                Layout.fillWidth: true

                GridLayout {
                    anchors.fill: parent
                    columns: root.width > 600 ? 2 : 1
                    RadioButton {
                        id: staticValueRadioButton
                        Layout.fillWidth: true
                        checked: true
                        text: qsTr("a static value:")
                        font.pixelSize: app.smallFont
                    }
                    RadioButton {
                        id: stateValueRadioButton
                        Layout.fillWidth: true
                        text: qsTr("another thing's state:")
                        font.pixelSize: app.smallFont
                        visible: engine.jsonRpcClient.ensureServerVersion("5.3")
                    }

                    ThinDivider { Layout.columnSpan: parent.columns }

                    StateDelegate {
                        id: staticValueParamDelegate
                        Layout.fillWidth: true
                        hoverEnabled: false
                        padding: 0
                        stateType: root.stateType
                        enabled: staticValueRadioButton.checked
                        nameVisible: false
                        visible: staticValueRadioButton.checked
                        placeholderText: qsTr("Insert value here")
                    }

                    NymeaItemDelegate {
                        id: statePickerDelegate
                        Layout.fillWidth: true
                        text: thingId === null || stateTypeId === null
                              ? qsTr("Select a state")
                              : thing.name + " - " + thing.thingClass.stateTypes.getStateType(stateTypeId).displayName
                        visible: stateValueRadioButton.checked

                        property var thingId: null
                        property var stateTypeId: null

                        readonly property Thing thing: engine.thingManager.things.getThing(thingId)

                        onClicked: {
                            var page = pageStack.push(Qt.resolvedUrl("SelectThingPage.qml"), {showStates: true, showEvents: false, showActions: false });
                            page.thingSelected.connect(function(thing) {
                                print("Thing selected", thing.name);
                                statePickerDelegate.thingId = thing.id
                                var selectStatePage = pageStack.replace(Qt.resolvedUrl("SelectStatePage.qml"), {thing: thing})
                                selectStatePage.stateSelected.connect(function(stateTypeId) {
                                    print("State selected", stateTypeId)
                                    pageStack.pop();
                                    statePickerDelegate.stateTypeId = stateTypeId;
                                })
                            })
                            page.backPressed.connect(function() {
                                pageStack.pop();
                            })
                        }
                    }
                }
            }

            Button {
                text: qsTr("OK")
                Layout.fillWidth: true
                Layout.margins: app.margins
                onClicked: {
                    print("saving")
                    root.stateDescriptor.valueOperator = operatorComboBox.model.get(operatorComboBox.currentIndex).value
                    print("operator:", root.stateDescriptor.valueOperator)
                    if (staticValueRadioButton.checked) {
                        print("static value:", staticValueParamDelegate.value)
                        root.stateDescriptor.value = staticValueParamDelegate.value
                    } else {
                        root.stateDescriptor.valueThingId = statePickerDelegate.thingId
                        root.stateDescriptor.valueStateTypeId = statePickerDelegate.stateTypeId
                    }
                    root.completed()
                }
            }

        }
    }
}
