import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

import "../style"

ItemDelegate {
    id: root

    property string recordTime: "—"
    property string recordFileName: "—"
    property string measurementType: "—"
    property string resultTag: "—"
    property string pointName: ""
    property var scalarValues: []
    property var rawResult: null
    property var analysisController: null
    property var dragPreviewController: null
    property bool spectrumDragEnabled: rawResult !== null
    property bool comparisonDragStarted: false
    property bool selectionClickSuppressed: false
    property int masterValuesCount: 0
    property bool selectedRecord: false
    property bool hasExceedance: false
    property color stateColor: "#788797"
    signal spectrumRequested()
    signal signalRequested()
    readonly property var displayedScalarValues:
        filteredScalarValues()
    readonly property int detailsCount:
        selectedRecord ? displayedScalarValues.length : 0

    function scalarName(item) {
        return String(item && (item.name || item.key)
                      ? (item.name || item.key) : "Значение")
    }

    function isPointLabelScalar(item) {
        var name = scalarName(item).trim().toLowerCase()
        if (name === "метка точки")
            return true
        var suffix = "/ метка точки"
        return name.length >= suffix.length
                && name.lastIndexOf(suffix)
                   === name.length - suffix.length
    }

    function filteredScalarValues() {
        var result = []
        for (var index = 0;
             scalarValues && index < scalarValues.length;
             ++index) {
            var item = scalarValues[index]
            if (!isPointLabelScalar(item))
                result.push(item)
        }
        return result
    }

    function scalarUnit(item) {
        if (!item)
            return ""
        var explicitUnit = String(item.unit || "").trim()
        if (explicitUnit.length > 0)
            return explicitUnit
        var match = scalarName(item).match(/\s*\(([^()]*)\)\s*$/)
        return match && String(match[1]).trim().length > 0
                ? String(match[1]).trim() : ""
    }

    function scalarDisplayName(item) {
        var name = scalarName(item)
        var unit = scalarUnit(item)
        if (unit.length === 0)
            return name
        var match = name.match(/\s*\(([^()]*)\)\s*$/)
        return match ? name.substring(0, match.index).trim() : name
    }

    function formatScalarValue(item) {
        if (!item || item.value === undefined || item.value === null)
            return "—"

        var value = item.value
        var name = String(item.name || item.key || "").toLowerCase()
        var number = Number(value)
        if ((name.indexOf("скз") >= 0 || name.indexOf("rms") >= 0)
                && isFinite(number)) {
            return number.toFixed(6)
        }
        return String(value)
    }

    width: ListView.view ? ListView.view.width : implicitWidth
    height: 58 + (detailsCount > 0 ? 8 + detailsCount * 24 : 0)
    leftPadding: 10
    rightPadding: 10
    hoverEnabled: true

    background: Rectangle {
        radius: 6
        color: root.selectedRecord
               ? "#D7E7F8"
               : root.hovered ? "#EDF4FC" : "transparent"
        border.width: root.selectedRecord ? 1 : 0
        border.color: "#005FCC"
    }

    contentItem: ColumnLayout {
        spacing: 2

        RowLayout {
            Layout.fillWidth: true

            Text {
                renderType: Text.NativeRendering
                Layout.fillWidth: true
                text: root.recordTime
                color: root.hasExceedance
                       ? root.stateColor : "#111827"
                font.pixelSize: 12
                font.bold: true
                elide: Text.ElideRight
            }

            Text {
                renderType: Text.NativeRendering
                text: root.resultTag !== "—" ? root.resultTag : ""
                color: "#526274"
                font.pixelSize: 10
                elide: Text.ElideRight
            }

        }

        Text {
            renderType: Text.NativeRendering
            Layout.fillWidth: true
            text: root.recordFileName
            color: root.hasExceedance
                   ? root.stateColor : "#405164"
            font.pixelSize: 11
            font.bold: root.hasExceedance
            elide: Text.ElideMiddle
        }

        Text {
            renderType: Text.NativeRendering
            Layout.fillWidth: true
            visible: root.measurementType !== "—"
            text: root.measurementType
            color: "#526274"
            font.pixelSize: 10
            elide: Text.ElideRight
        }

        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 1
            visible: root.detailsCount > 0
            color: "#AFC4DA"
        }


        Repeater {
            model: root.selectedRecord
                   ? root.displayedScalarValues : []

            delegate: RowLayout {
                id: scalarRow

                required property var modelData

                Layout.fillWidth: true

                Text {
                    renderType: Text.NativeRendering
                    Layout.fillWidth: true
                    text: root.scalarDisplayName(scalarRow.modelData)
                    color: "#526274"
                    font.pixelSize: 10
                    elide: Text.ElideRight
                }

                Text {
                    renderType: Text.NativeRendering
                    text: root.formatScalarValue(scalarRow.modelData)
                          + (root.scalarUnit(scalarRow.modelData)
                             ? " " + root.scalarUnit(
                                 scalarRow.modelData) : "")
                    color: "#111827"
                    font.pixelSize: 10
                    font.bold: true
                }
            }
        }

    }

    MouseArea {
        id: recordDragArea

        objectName: "spectrumDragArea"
        z: 100
        anchors.fill: parent
        enabled: root.spectrumDragEnabled
        acceptedButtons: Qt.LeftButton
        hoverEnabled: true
        preventStealing: false
        cursorShape: drag.active
                     ? Qt.ClosedHandCursor : Qt.ArrowCursor
        drag.target: dragProxy
        drag.axis: Drag.XAndYAxis
        drag.threshold: 4
        drag.smoothed: false

        onPressed: {
            selectionSuppressionTimer.stop()
            root.selectionClickSuppressed = false
            root.comparisonDragStarted = false
            var overlayPosition = root.mapToItem(
                        dragProxy.parent, 0, 0)
            dragProxy.x = overlayPosition.x
            dragProxy.y = overlayPosition.y
            if (root.analysisController) {
                root.analysisController.prepareComparisonDrag(
                            root.rawResult, root.pointName)
            }
        }

        onClicked: {
            if (root.analysisController)
                root.analysisController.cancelComparisonDrag()
            if (!root.selectionClickSuppressed)
                root.clicked()
        }

        onPositionChanged: function(mouse) {
            if (!drag.active)
                return

            var globalPosition = recordDragArea.mapToGlobal(
                        mouse.x, mouse.y)
            if (!root.comparisonDragStarted) {
                root.comparisonDragStarted = true
                root.selectionClickSuppressed = true
                if (root.analysisController)
                    root.analysisController.beginComparisonDrag()
                if (root.dragPreviewController) {
                    root.dragPreviewController.showDragPreview(
                                root.pointName + " · "
                                + root.recordTime,
                                globalPosition.x,
                                globalPosition.y,
                                Math.min(root.width, 360))
                }
            } else if (root.dragPreviewController) {
                root.dragPreviewController.moveDragPreview(
                            globalPosition.x, globalPosition.y)
            }
        }

        onReleased: function(mouse) {
            if (root.dragPreviewController)
                root.dragPreviewController.hideDragPreview()
            if (dragProxy.Drag.active)
                dragProxy.Drag.drop()
            if (root.comparisonDragStarted
                    && root.analysisController) {
                var globalPosition = recordDragArea.mapToGlobal(
                            mouse.x, mouse.y)
                if (root.analysisController
                        .pendingComparisonResult !== null) {
                    root.analysisController.finishComparisonDragAt(
                                globalPosition.x,
                                globalPosition.y)
                } else {
                    root.analysisController.cancelComparisonDrag()
                }
            }
            root.comparisonDragStarted = false
            if (root.selectionClickSuppressed)
                selectionSuppressionTimer.restart()
        }

        onCanceled: {
            if (root.dragPreviewController)
                root.dragPreviewController.hideDragPreview()
            root.comparisonDragStarted = false
            if (root.analysisController)
                root.analysisController.cancelComparisonDrag()
            if (root.selectionClickSuppressed)
                selectionSuppressionTimer.restart()
        }
    }

    MouseArea {
        id: recordContextArea

        z: 110
        anchors.fill: parent
        acceptedButtons: Qt.RightButton
        hoverEnabled: false
        preventStealing: true

        onClicked: function(mouse) {
            var globalPosition = recordContextArea.mapToGlobal(
                        mouse.x, mouse.y)
            var overlayPosition = Overlay.overlay.mapFromGlobal(
                        globalPosition.x, globalPosition.y)
            recordContextMenu.x = Math.round(overlayPosition.x)
            recordContextMenu.y = Math.round(overlayPosition.y)
            recordContextMenu.open()
        }
    }

    Menu {
        id: recordContextMenu

        parent: Overlay.overlay
        width: 210
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside

        background: Rectangle {
            radius: 6
            color: "#FFFFFF"
            border.width: 1
            border.color: "#AFC4DA"
        }

        AppMenuItem {
            text: "Показать спектр"
            onTriggered: root.spectrumRequested()
        }

        AppMenuItem {
            text: "Показать сигнал"
            onTriggered: root.signalRequested()
        }
    }

    Item {
        id: dragProxy

        parent: Overlay.overlay ? Overlay.overlay : root
        objectName: "spectrumDragProxy"
        z: 1000000
        x: 0
        y: 0
        width: root.width
        height: 42
        visible: recordDragArea.drag.active

        Drag.active: recordDragArea.drag.active
        Drag.source: root
        Drag.keys: ["vibro-spectrum-record"]
        Drag.dragType: Drag.Internal
        Drag.mimeData: {
            "application/x-vibro-spectrum-record":
                root.pointName + "|" + root.recordTime
        }
        Drag.supportedActions: Qt.CopyAction
        Drag.proposedAction: Qt.CopyAction
        Drag.hotSpot.x: width / 2
        Drag.hotSpot.y: height / 2
        Drag.onDragFinished: {
            dragProxy.x = 0
            dragProxy.y = 0
        }

        Rectangle {
            visible: !root.dragPreviewController
            anchors.fill: parent
            radius: 6
            color: "#EAF2FB"
            border.color: "#005FCC"
            opacity: 0.94

            Text {
                renderType: Text.NativeRendering
                anchors.fill: parent
                anchors.margins: 8
                text: root.pointName + " · " + root.recordTime
                color: "#111827"
                font.pixelSize: 12
                font.bold: true
                verticalAlignment: Text.AlignVCenter
                elide: Text.ElideRight
            }
        }
    }

    Timer {
        id: selectionSuppressionTimer

        interval: 700
        repeat: false
        onTriggered:
            root.selectionClickSuppressed = false
    }

}
