import QtQuick 2.0

Item {
    id: buzzerConn
    height: 0
    width: 0
    opacity: 0
    visible: false

    signal pushed()
    property bool connected: false
    property var status: {'status': buzzerConn.state, 'progress': get_progress()}

    Timer {
        //timer that refreshes the connection state to the buzzer
        id: connectionRefreshTimer
        running: root.state !== "RUNNING" && root.state !== "STARTING" && buzzerConn.status !== "connecting"
        repeat: false
        interval: 1000
        onTriggered: {
            _cppBuzzerConn.refresh()
            if(!_cppBuzzerConn.get("connected") && buzzerConn.state !== "connecting"){
                buzzerConn.state = "disconnected"
            }

            connectionRefreshTimer.start()
        }
    }

    Timer {
        //timer that checks, if the button has been pushed
        id: running_refresh_timer
        running: root.state === "RUNNING"
        repeat: false
        interval: 1

        onTriggered: {
            if(_cppBuzzerConn.buzzer_triggered()){
                buzzerConn.pushed()

            }
            if(root.state === "RUNNING"){
                running_refresh_timer.start()
            }
        }
    }

    Timer {
        id: prog_refresh
        running: buzzerConn.state === "connecting"
        interval: 1
        repeat: true
        onTriggered: {
            buzzerConn.status.progress = get_progress()
        }
    }

    states: [
        State {
            name: "disconnected"
            PropertyChanges {
                target: buzzerConn
            }
        },
        State {
            name: "connecting"
            PropertyChanges {
                target: buzzerConn
            }
        },
        State {
            name: "connected"
            PropertyChanges {
                target: buzzerConn
            }
        }
    ]

    function connect(){
        buzzerConn.state = "connecting"
        if(_cppBuzzerConn.connect()){
            buzzerConn.state = "connected"
            return(true)
        }
        else {
            buzzerConn.state = "disconnected"
            return(false)
        }


    }

    function get_progress(){
        return(_cppBuzzerConn.get("connection_progress"))
    }
}
