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 {
            render(newState);
            refreshPopup(newState);
        }
    });
}

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

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

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

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;
        }
    });
}
