import QtQuick 2.12
import QtCharts 2.3

import Utils 1.0

ChartView {
    id: chart

    antialiasing: true
    backgroundColor: Palette.backgroundColor
    margins.left: 20

    legend.visible: false
    legend.alignment: Qt.AlignRight
    legend.markerShape: Legend.MarkerShapeCircle

    property AbstractAxis xAxis: valueAxisX
    property AbstractAxis yAxis: valueAxisY

    property int defaultXMax: 10
    property int defaultYMax: 1
    property bool autoScaling: true

    ValueAxis {
        id: valueAxisX
        min: 0
        max: chart.defaultXMax
        tickCount: 8
        gridVisible: false
        gridLineColor: Palette.borderColor
        labelsColor: Palette.contentTextColor
        labelsFont.pixelSize: 18
        color: Palette.borderColor
        titleVisible: false
    }

    ValueAxis {
        id: valueAxisY
        min: 0
        max: chart.defaultYMax
        tickCount: 6
        labelsColor: Palette.contentTextColor
        labelsFont.pixelSize: 18
        color: Palette.borderColor
        titleVisible: false
    }

    MouseArea {
        id: chartMouseAreaA
        anchors.fill: parent
        acceptedButtons: Qt.LeftButton

        property real lastMouseX: 0
        property real lastMouseY: 0

        property real scrollThreshold: 0

        onMouseXChanged: {
            if ((mouse.buttons & Qt.LeftButton) == Qt.LeftButton) {
                if (mouseX - lastMouseX > scrollThreshold) {
                    chart.scrollLeft(mouseX - lastMouseX)
                    lastMouseX = mouseX
                    chart.autoScaling = false
                } else if (mouseX - lastMouseX < scrollThreshold) {
                    chart.scrollRight(lastMouseX - mouseX)
                    lastMouseX = mouseX
                    chart.autoScaling = false
                }
            }
        }
        onMouseYChanged: {
            if ((mouse.buttons & Qt.LeftButton) == Qt.LeftButton) {
                if (mouseY - lastMouseY > scrollThreshold) {
                    chart.scrollUp(mouseY - lastMouseY)
                    lastMouseY = mouseY
                    chart.autoScaling = false
                } else if (mouseY - lastMouseY < scrollThreshold) {
                    chart.scrollDown(lastMouseY - mouseY)
                    lastMouseY = mouseY
                    chart.autoScaling = false
                }
            }
        }
        onPressed: {
            if (mouse.button === Qt.LeftButton) {
                lastMouseX = mouseX
                lastMouseY = mouseY
            }
        }
        onWheel: {
            if (wheel.angleDelta.y > 0) {
                chart.zoomIn()
                chart.autoScaling = false
            } else {
                chart.zoomOut()
                chart.autoScaling = false
            }
        }
    }
}
