import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Controls.Material 2.12

Item {
    id: control

    property alias text: firstLabel.text
    property alias font: firstLabel.font
    property alias verticalAlignment: firstLabel.verticalAlignment
    property int spacing: 30

    property MovingLabel syncWithLabel
    property int _spacing: syncWithLabel && syncWithLabel._labelWidth > _labelWidth ? (syncWithLabel._labelWidth - _labelWidth + syncWithLabel.spacing) : spacing
    property alias _labelWidth: firstLabel.width

    signal linkActivated(string link)

    clip: true
    height: firstLabel.height

    onTextChanged: {
        _resetScroll()
        if(control.syncWithLabel)
            control.syncWithLabel._resetScroll()
    }

    function startScroll(triggerSyncedLabel=true) {
        if(control.syncWithLabel && triggerSyncedLabel)
            control.syncWithLabel.startScroll(false)
        if(control.width < firstLabel.width && !scrollAnimation.running)
            scrollAnimation.start()
    }

    function _resetScroll() {
        scrollAnimation.stop()
        firstLabel.anchors.leftMargin = 0
    }

    Label {
        id: firstLabel

        anchors {
            left: parent.left
            verticalCenter: parent.verticalCenter
        }

        onLinkActivated: control.onLinkActivated(link)
    }

    Label {
        id: secondLabel

        anchors {
            left: firstLabel.right
            leftMargin: control._spacing
            verticalCenter: firstLabel.verticalCenter
        }

        visible: scrollAnimation.running

        font: firstLabel.font
        text: firstLabel.text
        verticalAlignment: firstLabel.verticalAlignment
        elide: firstLabel.elide
        bottomPadding: firstLabel.bottomPadding
        padding: firstLabel.padding

        onLinkActivated: control.onLinkActivated(link)
    }

    MouseArea {
        anchors.fill: parent
        onClicked: control.startScroll()
    }

    NumberAnimation {
        id: scrollAnimation
        target: firstLabel
        property: "anchors.leftMargin"
        from: 0
        to: -(firstLabel.width + control._spacing)
        duration: (to / -100) * 1500

        onRunningChanged: {
            if(!running)
                control._resetScroll()
        }
    }
}
