import QtQml

import "../utils"

QtObject {
    id: controller

    readonly property DateTimeUtils dateTimeUtils: DateTimeUtils {}

    property var recordsModel: null
    property var recordsController: null
    property var resultAdapter: null

    property var availableTags: []
    property var tagOptions: []
    property var metrics: []
    property var metricOptions: []
    property var points: []
    property var scalarValuesCache: ({})
    property string scalarValuesDatasetSignature: ""
    property string selectedTag: ""
    property string selectedMetricKey: ""
    property string selectedMetricName: ""
    property string statusMessage: "Мастер-значения ещё не построены"
    readonly property bool pointNodeSelected:
        isPointNode(recordsController
                    ? recordsController.currentNode : null)

    signal trendUpdated(int pointCount)
    signal sourceRecordRequested(int recordIndex)

    readonly property Connections recordsConnections: Connections {
        target: controller.recordsController
        ignoreUnknownSignals: true

        function onResultTagChanged() {
            controller.refreshAvailableTags()
        }

        function onAvailableTagsChanged() {
            controller.refreshAvailableTags()
        }
    }

    function rebuild() {
        refreshAvailableTags()

        var metricMap = ({})
        var metricOrder = []

        if (!pointNodeSelected) {
            clearTrend("Мастер-значения доступны только для точек")
            return
        }

        if (!recordsModel || !resultAdapter) {
            clearTrend("Источник записей не подключён")
            return
        }

        refreshScalarValuesCacheScope()

        for (var recordIndex = 0;
             recordIndex < recordsModel.count; ++recordIndex) {
            var recordSummary = recordsModel.get(recordIndex)
            if (selectedTag.length > 0
                    && String(recordSummary.tag || "") !== selectedTag)
                continue

            var time = recordSummary.recordTimeValid === true
                    ? Number(recordSummary.recordTimestamp)
                    : dateTimeUtils.timestamp(recordSummary.recordTime)
            if (!isFinite(time))
                continue

            var values = scalarValuesForRecord(recordSummary)
            for (var valueIndex = 0;
                 valueIndex < values.length; ++valueIndex) {
                var entry = values[valueIndex]
                var numericValue = numeric(entry.value)
                if (!isFinite(numericValue))
                    continue

                var key = String(entry.key || entry.name
                                 || "Значение")
                if (!metricMap[key]) {
                    metricMap[key] = {
                        key: key,
                        name: String(entry.name || key),
                        unit: entry.unit ? String(entry.unit) : "",
                        points: [],
                        descending: true
                    }
                    metricOrder.push(key)
                }
                var metricPoints = metricMap[key].points
                if (metricPoints.length > 0
                        && Number(metricPoints[
                                      metricPoints.length - 1].x) < time) {
                    metricMap[key].descending = false
                }
                metricPoints.push({
                    x: time,
                    y: numericValue,
                    tag: String(recordSummary.tag || ""),
                    hasExceedance: Boolean(
                                           recordSummary.hasExceedance),
                    stateColor: String(
                                    recordSummary.stateColor || ""),
                    statePriority: Number(
                                       recordSummary.statePriority),
                    recordIndex: recordIndex,
                    recordKey: String(recordSummary.key),
                    recordTime: String(recordSummary.recordTime)
                })
            }
        }

        var builtMetrics = []
        for (var orderIndex = 0;
             orderIndex < metricOrder.length; ++orderIndex) {
            var metric = metricMap[metricOrder[orderIndex]]
            if (metric.descending)
                metric.points.reverse()
            else
                metric.points.sort(function(left, right) {
                    return left.x - right.x
                })
            if (metric.points.length > 0) {
                builtMetrics.push({
                    key: metric.key,
                    name: metric.name
                          + (metric.unit.length > 0
                             ? " (" + metric.unit + ")" : ""),
                    unit: metric.unit,
                    pointCount: metric.points.length,
                    sourcePoints: metric.points
                })
            }
        }

        metrics = builtMetrics
        var builtMetricOptions = []
        for (var metricOptionIndex = 0;
             metricOptionIndex < builtMetrics.length;
             ++metricOptionIndex) {
            builtMetricOptions.push(
                        String(builtMetrics[metricOptionIndex].name || ""))
        }
        metricOptions = builtMetricOptions
        var selectedIndex = metricIndexByKey(selectedMetricKey)
        if (selectedIndex < 0)
            selectedIndex = metrics.length > 0 ? 0 : -1
        selectMetric(selectedIndex)
    }

    function refreshAvailableTags() {
        var source = recordsController
                ? recordsController.availableTags : []
        var tags = []
        var seen = ({})

        if (source) {
            for (var index = 0; index < source.length; ++index) {
                var tag = String(source[index] || "").trim()
                if (tag.length === 0 || seen[tag] === true)
                    continue
                seen[tag] = true
                tags.push(tag)
            }
        }

        availableTags = tags
        tagOptions = tags
        var recordsTag = recordsController
                ? String(recordsController.resultTag || "").trim() : ""
        if (recordsTag.length > 0
                && tags.indexOf(recordsTag) >= 0) {
            selectedTag = recordsTag
        } else if (tags.indexOf(selectedTag) < 0) {
            selectedTag = tags.length > 0 ? tags[0] : ""
        }
    }

    function selectTag(tag) {
        var value = String(tag || "").trim()
        if (availableTags.indexOf(value) < 0)
            return false

        selectedTag = value
        if (!recordsController) {
            rebuild()
            return true
        }

        recordsController.setPreferredResultTag(value)
        return recordsController.load(
                    recordsController.currentNode,
                    recordsController.dateFrom,
                    recordsController.dateTo,
                    value, recordsController.loadLimit, false)
    }

    function isPointNode(node) {
        return recordsController
                && typeof recordsController.isPointNode === "function"
                ? recordsController.isPointNode(node) : false
    }

    function clearTrend(message) {
        metrics = []
        metricOptions = []
        points = []
        selectedMetricKey = ""
        selectedMetricName = ""
        statusMessage = String(message)
        trendUpdated(0)
    }

    function selectMetric(index) {
        if (index < 0 || index >= metrics.length) {
            selectedMetricKey = ""
            selectedMetricName = ""
            points = []
            statusMessage = "Мастер-значения не найдены"
            trendUpdated(0)
            return false
        }

        var metric = metrics[index]
        selectedMetricKey = metric.key
        selectedMetricName = metric.name
        points = metric.sourcePoints
        statusMessage = "Точек: " + points.length
        trendUpdated(points.length)
        return true
    }

    function activatePoint(point) {
        if (!point)
            return false
        var index = Number(point.recordIndex)
        if (!isFinite(index))
            return false
        sourceRecordRequested(index)
        return recordsController
                ? recordsController.select(index) : false
    }

    function metricIndexByKey(key) {
        if (!key)
            return -1
        for (var i = 0; i < metrics.length; ++i) {
            if (metrics[i].key === key)
                return i
        }
        return -1
    }

    function numeric(value) {
        if (value === undefined || value === null
                || typeof value === "boolean")
            return NaN
        if (typeof value === "string")
            value = value.replace(",", ".").trim()
        var result = Number(value)
        return isFinite(result) ? result : NaN
    }

    function scalarValuesForRecord(recordSummary) {
        var rawResult = recordSummary ? recordSummary.rawResult : null
        if (!rawResult)
            return []
        var key = String(recordSummary.key || "")
        var cached = key.length > 0 ? scalarValuesCache[key] : null
        if (cached && cached.rawResult === rawResult)
            return cached.values
        var values = resultAdapter.extractScalarValues(rawResult)
        if (key.length > 0) {
            // Internal cache; no binding observes individual entries.
            scalarValuesCache[key] = {
                rawResult: rawResult,
                values: values
            }
        }
        return values
    }

    function refreshScalarValuesCacheScope() {
        var count = recordsModel ? Number(recordsModel.count) : 0
        var firstKey = count > 0
                ? String(recordsModel.get(0).key || "") : ""
        var lastKey = count > 1
                ? String(recordsModel.get(count - 1).key || "") : firstKey
        var signature = count + "|" + firstKey + "|" + lastKey
        if (signature === scalarValuesDatasetSignature)
            return
        scalarValuesDatasetSignature = signature
        scalarValuesCache = ({})
    }

}
