import QtQuick 2.9
import QtMultimedia 5.8
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import "."
import "./components"
import "./styles"
import com.itsblue.speedclimbingstopwatch 1.0

Item {
    id: control
    property color color
    property string text: qsTr("Click start to start")
    property string elide
    property int pixelSize: 100
    property int scale: 1

    property var toppadConn
    property var startpadConn
    property var baseConn

    property double startTime: 0
    property double stopTime: 0
    property double stoppedTime: 0
    property double reactionTime: 0

    property double currTime: 0

    signal stopped()
    signal startCanceled(bool falseStart)
    signal stateChanged(var newState)
    anchors.fill: parent
    state: "IDLE"

    Label {
        id: time
        text: timerBackend.state === "STARTING" ? control.text:timerBackend.text
        scale: parent.scale
        anchors.centerIn: parent
        font.pixelSize: parent.pixelSize
        elide: parent.elide
        color: appTheme.style.textColor
        Behavior on text {
            enabled: timerBackend.state !== "RUNNING"
            FadeAnimation {
                target: time
            }
        }

    }
/*
    SpeedTimerBackend {
        id: timerBackend

        onStateChanged: {
            control.stateChanged(newState)
        }

        onStartCanceled: {
            console.log("start cnaceled")
            control.startCanceled(falseStart)
        }
    }*/

    function getState(){
        return(timerBackend.getState())
    }

    function setStarting(){
        timerBackend.setStarting()
    }

    function start(inMilliSeconds){
        startTimer.interval = inMilliSeconds
        startTimer.start()
    }

    function stop(type){
        timerBackend.stop(type)
    }

    function reset(){
        timerBackend.reset()
    }

    function handleStartpad(){
        console.log("startpad triggered")
        var offset = control.startpadConn.offset
        var last_pressed = control.startpadConn.lastTriggered
        var trigger_time = (last_pressed + offset)
        control.reactionTime = trigger_time - control.startTime
        if(trigger_time - control.startTime <= 0){
            stop("false")
        }
    }

    function handleToppad(){
        console.log(lastTriggered)
        stop("toppad")
    }

    Timer {
        id: startTimer
        running: false
        repeat: false
        onTriggered: {
            timerBackend.start()
            console.log("started")
        }
    }
}
