// Idea from:
// https://stackoverflow.com/questions/42992067/qtquick-dragging-mapquickitem-on-a-map

import QtQuick      2.3
import QtLocation   5.3

import QGroundControl               1.0
import QGroundControl.ScreenTools   1.0
import QGroundControl.Controls      1.0

Rectangle {
    id:             root

    property var anchor: undefined
    property bool draggable: true
    readonly property bool dragged: mouseArea.drag.active

    signal dragStart
    signal dragStop
    signal clicked

    property bool _mobile:                  ScreenTools.isMobile
    property real _touchWidth:              Math.max(anchor.width, ScreenTools.minTouchPixels)
    property real _touchHeight:             Math.max(anchor.height, ScreenTools.minTouchPixels)
    property real _touchMarginHorizontal:   _mobile ? (_touchWidth - anchor.width) / 2 : 0
    property real _touchMarginVertical:     _mobile ? (_touchHeight - anchor.height) / 2 : 0


    x:              anchor.x - _touchMarginHorizontal
    y:              anchor.y - _touchMarginVertical
    width:          anchor.width + (_touchMarginHorizontal * 2)
    height:         anchor.height + (_touchMarginVertical * 2)
    color:          "transparent"
    z:              QGroundControl.zOrderMapItems + 1

    Component.onCompleted: {
        console.assert(anchor !== undefined, "please set the anchor property")
    }


    onDraggedChanged: {
        if (dragged) {
            dragStart()
        } else {
            dragStop()
        }
    }

    QGCMouseArea {
        id: mouseArea
        enabled: draggable
        preventStealing:    true
        drag.target: root
        drag.threshold: 0
        anchors.fill: parent
        cursorShape: draggable ?
                         (dragged ? Qt.ClosedHandCursor : Qt.OpenHandCursor)
                       : Qt.ArrowCursor
        onClicked: {
            focus = true
            root.clicked()
        }

    }

    Connections {
        target: anchor
        onXChanged: if (!dragged) x = anchor.x - _touchMarginHorizontal
        onYChanged: if (!dragged) y = anchor.y - _touchMarginVertical
    }

    onXChanged: if (dragged) anchor.x = x + _touchMarginHorizontal
    onYChanged: if (dragged) anchor.y = y + _touchMarginVertical

    Drag.active: true
}
