import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

import "../charts"
import "../style"

Rectangle {
    id: root

    property var trendController: null
    property bool independentMetricSelection: false
    property string localSelectedMetricKey: ""
    property bool dragToDetachEnabled: false
    property var moveWindow: null
    property bool locked: false
    property bool lockButtonVisible: false
    readonly property bool trendsAvailable:
        trendController && trendController.pointNodeSelected

    signal detachRequested(real globalX, real globalY,
                           real pressOffsetX, real pressOffsetY)
    signal lockToggled(bool locked)
    signal additionalWindowRequested(string metricKey)

    readonly property string activeMetricKey:
        independentMetricSelection
        ? localSelectedMetricKey
        : (trendController ? trendController.selectedMetricKey : "")
    readonly property string activeMetricName: {
        if (!trendController)
            return ""
        if (!independentMetricSelection)
            return trendController.selectedMetricName
        var index = trendController.metricIndexByKey(localSelectedMetricKey)
        return index >= 0 ? String(trendController.metrics[index].name) : ""
    }
    readonly property var displayedPoints: {
        if (!trendController)
            return []
        if (!independentMetricSelection)
            return trendController.points
        var index = trendController.metricIndexByKey(localSelectedMetricKey)
        return index >= 0 ? trendController.metrics[index].sourcePoints : []
    }
    readonly property string displayedStatusMessage:
        independentMetricSelection
        ? "Точек: " + displayedPoints.length
        : (trendController ? trendController.statusMessage : "")

    function ensureLocalMetricSelection() {
        if (!independentMetricSelection || !trendController)
            return
        if (trendController.metricIndexByKey(localSelectedMetricKey) >= 0)
            return
        if (trendController.metricIndexByKey(
                    trendController.selectedMetricKey) >= 0) {
            localSelectedMetricKey = trendController.selectedMetricKey
        } else {
            localSelectedMetricKey = trendController.metrics.length > 0
                    ? String(trendController.metrics[0].key) : ""
        }
    }

    function selectMetric(index) {
        if (!trendController)
            return
        if (!independentMetricSelection) {
            trendController.selectMetric(index)
            return
        }
        if (index < 0 || index >= trendController.metrics.length)
            return
        localSelectedMetricKey = String(trendController.metrics[index].key)
    }

    function syncSelectedTag() {
        if (!trendController || trendController.selectedTag.length === 0) {
            trendTagCombo.currentIndex = -1
            return
        }

        var selectedIndex = -1
        for (var index = 0;
             index < trendController.availableTags.length;
             ++index) {
            if (String(trendController.availableTags[index])
                    === trendController.selectedTag) {
                selectedIndex = index
                break
            }
        }
        trendTagCombo.currentIndex = selectedIndex
    }

    function selectedTagValue() {
        if (!trendController || trendTagCombo.currentIndex < 0)
            return ""
        return trendTagCombo.currentText
    }

    function syncSelectedMetric() {
        if (!trendController
                || root.activeMetricKey.length === 0) {
            masterValueCombo.currentIndex = -1
            return
        }

        var selectedIndex = -1
        for (var index = 0;
             index < trendController.metrics.length; ++index) {
            if (String(trendController.metrics[index].key)
                    === root.activeMetricKey) {
                selectedIndex = index
                break
            }
        }
        masterValueCombo.currentIndex = selectedIndex
    }

    Connections {
        target: root.trendController

        function onAvailableTagsChanged() {
            root.syncSelectedTag()
        }

        function onTagOptionsChanged() {
            root.syncSelectedTag()
        }

        function onSelectedTagChanged() {
            root.syncSelectedTag()
        }

        function onMetricsChanged() {
            root.ensureLocalMetricSelection()
            root.syncSelectedMetric()
        }

        function onSelectedMetricKeyChanged() {
            root.syncSelectedMetric()
        }
    }

    onTrendControllerChanged: {
        ensureLocalMetricSelection()
        syncSelectedTag()
        syncSelectedMetric()
    }

    onIndependentMetricSelectionChanged: {
        ensureLocalMetricSelection()
        syncSelectedMetric()
    }

    onLocalSelectedMetricKeyChanged: syncSelectedMetric()

    Component.onCompleted: {
        ensureLocalMetricSelection()
        syncSelectedTag()
        syncSelectedMetric()
    }

    color: "#F8FAFC"
    border.color: "#788797"
    radius: 8
    clip: true

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 8
        spacing: 7
        visible: root.trendsAvailable

        RowLayout {
            Layout.fillWidth: true
            Layout.preferredHeight: 38
            Layout.minimumHeight: 38
            Layout.maximumHeight: 38
            spacing: 8

            WindowLockButton {
                visible: root.lockButtonVisible
                Layout.preferredWidth: visible ? 36 : 0
                Layout.minimumWidth: visible ? 36 : 0
                Layout.maximumWidth: visible ? 36 : 0
                Layout.preferredHeight: 36
                locked: root.locked
                onLockToggled: function(locked) {
                    root.lockToggled(locked)
                }
            }

            Label {
                renderType: Text.NativeRendering
                Layout.minimumWidth: 0
                text: "Мастер-значения"
                color: "#405164"
                font.pixelSize: 13
                font.bold: true
                elide: Text.ElideRight
            }

            PanelDragArea {
                Layout.fillWidth: true
                Layout.fillHeight: true
                dragToDetachEnabled: root.dragToDetachEnabled && !root.locked
                moveWindow: root.locked ? null : root.moveWindow
                onDetachRequested: function(globalX, globalY,
                                             pressOffsetX, pressOffsetY) {
                    root.detachRequested(globalX, globalY,
                                         pressOffsetX, pressOffsetY)
                }
            }

            Label {
                renderType: Text.NativeRendering
                Layout.minimumWidth: 0
                Layout.maximumWidth: 110
                text: root.displayedStatusMessage
                color: "#405164"
                font.pixelSize: 11
                horizontalAlignment: Text.AlignRight
                elide: Text.ElideRight
            }
        }

        RowLayout {
            Layout.fillWidth: true
            Layout.preferredHeight: 38
            Layout.minimumHeight: 38
            Layout.maximumHeight: 38
            spacing: 8

            Label {
                renderType: Text.NativeRendering
                text: "Тег записи"
                color: "#405164"
                font.pixelSize: 12
            }

            AppComboBox {
                id: trendTagCombo

                Layout.fillWidth: true
                Layout.preferredWidth: 160
                Layout.minimumWidth: 80
                Layout.preferredHeight: 32
                Layout.minimumHeight: 32
                Layout.maximumHeight: 32
                model: root.trendController
                       ? root.trendController.tagOptions : []
                enabled: count > 0
                displayText: currentIndex >= 0
                             ? currentText : "Выберите тег"
                leftPadding: 12
                rightPadding: 32
                font.pixelSize: 12

                onActivated: {
                    if (root.trendController)
                        root.trendController.selectTag(
                                    root.selectedTagValue())
                }

                indicator: Text {
                    renderType: Text.NativeRendering
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    text: trendTagCombo.popup.visible ? "▴" : "▾"
                    color: trendTagCombo.enabled
                           ? "#005FCC" : "#94A3B8"
                    font.pixelSize: 15
                    font.bold: true
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }

                background: Rectangle {
                    radius: 5
                    color: "#F1F4F8"
                    border.width: trendTagCombo.activeFocus ? 2 : 1
                    border.color: trendTagCombo.activeFocus
                                  ? "#005FCC" : "#9AA8B7"
                }
            }

            Label {
                renderType: Text.NativeRendering
                text: "Мастер-значение"
                color: "#405164"
                font.pixelSize: 12
            }

            AppComboBox {
                id: masterValueCombo

                Layout.fillWidth: true
                Layout.preferredWidth: 300
                Layout.minimumWidth: 100
                Layout.preferredHeight: 32
                Layout.minimumHeight: 32
                Layout.maximumHeight: 32
                model: root.trendController
                       ? root.trendController.metrics : []
                textRole: "name"
                valueRole: "key"
                enabled: count > 0
                displayText: currentIndex >= 0
                             ? currentText : "Выберите мастер-значение"
                popupScrollBarEnabled: true

                onActivated: function(index) {
                    root.selectMetric(index)
                }

                AppToolTip {
                    target: masterValueCombo
                    text: masterValueCombo.currentIndex >= 0
                          ? masterValueCombo.currentText : ""
                }
            }
        }

        TrendChart {
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.minimumWidth: 0
            Layout.minimumHeight: 120
            points: root.displayedPoints
            primaryTag: root.trendController
                        && root.trendController.availableTags.length > 0
                        ? String(root.trendController.availableTags[0]) : ""
            onPointActivated: function(point) {
                if (root.trendController)
                    root.trendController.activatePoint(point)
            }
        }

        Label {
            renderType: Text.NativeRendering
            Layout.fillWidth: true
            Layout.minimumWidth: 0
            text: "Щёлкните по точке — открыть запись. ПКМ по окну — открыть ещё один график."
            color: "#405164"
            font.pixelSize: 11
            elide: Text.ElideRight
        }
    }

    TapHandler {
        acceptedButtons: Qt.RightButton
        gesturePolicy: TapHandler.ReleaseWithinBounds
        onTapped: root.additionalWindowRequested(root.activeMetricKey)
    }

    Label {
        renderType: Text.NativeRendering
        anchors.centerIn: parent
        width: Math.max(0, parent.width - 32)
        visible: !root.trendsAvailable
        text: "Мастер-значения доступны только для точек"
        color: "#526274"
        font.pixelSize: 13
        horizontalAlignment: Text.AlignHCenter
        wrapMode: Text.WordWrap
    }
}
