document.getElementById("play-button").addEventListener("click", handlePlay);
document.getElementById("stop-button").addEventListener("click", handleStop);
document.getElementById("play-restart").addEventListener("click", handleRestart);
document.getElementById("trash").addEventListener("click", handleTrash);
document.getElementById("mediaRecording").addEventListener("change", handleMediaRecord);


function handlePlay() {
    sendMessage({
        kind: 'startExploration'
    })
    .then (newState => {
        if (newState.error) {
            getState();
        } else {
            state = newState;
            //console.log('state:',state);
            render();
            refreshPopup(state);
        }
    });
}

function handleStop() {
    sendMessage({
        kind: 'stopExploration'
    })
    .then(newState => {
        if (!newState) {
            console.log(runtime.lastError);
        } else {
            state = newState;
        }
        //console.log('state:',state);
        render()
        refreshPopup(state)
    });
}

function handleRestart() {
    sendMessage({
        kind: 'restartExploration'
    })
    .then(newState => {
        state = newState;
        render()
        refreshPopup(state)
    });
}

function handleTrash() {
    sendMessage({
        kind: 'removeExploration'
    })
    .then(newState => {
        state = newState;
        render()
        refreshPopup(state)
    });
}

function refreshPopup(state) {
    if (state.isRecording) {
        document.getElementById("recording-status").innerHTML = "recording";
        document.getElementById("play-button").classList.add("btn-success")
    } else {
        document.getElementById("recording-status").innerHTML = "not recording";
        document.getElementById("play-button").classList.remove("btn-success")
    }
}

function handleMediaRecord() {
    sendMessage({
        kind: 'setRecordMediaStatus',
        recordMediaStatus:document.getElementById("mediaRecording").checked
    })
    .then(response => {
        if (response === "notok") {
            document.getElementById("mediaRecording").checked = false;
        }
    });
}

