document.getElementById("connectionSignIn").addEventListener("click", handleConnection);
document.getElementById("connectionForm").addEventListener("submit", handleConnection);
document.getElementById("connectionSignOut").addEventListener("click", handleDisconnection);
document.getElementById("connectionSync").addEventListener("click", handleSync);
document.getElementById("openSessionWindow").addEventListener("click", handleOpenSessionWindow);


function handleConnection(e) {
    e.preventDefault()
    const code = document.getElementById("connectionCodeInput").value
    if (!code) {
        return
    }
    chrome.runtime.sendMessage({
        kind: "connect",
        connectionCode: code
    }, {}, (response) => {
        if (response  && response === "ok") {
            getState();
        } else {
            document.getElementById('connexionMessage').innerHTML = 'Unknown Connection code. Please try again.';
        }
    });
}

function handleDisconnection(e) {
    e.preventDefault()
    chrome.runtime.sendMessage({
        kind: "disconnect",
    }, {}, response => {
        if (!response) {
            reject(`Background does not answer`);
        }
        if (response.error) {
            reject(response.error);
        } else {
            renderNotConnected();
            connectionCode = undefined
        }
    });
}

function handleSync(e) {
    e.preventDefault();
    chrome.runtime.sendMessage({
        kind: "reloadWebSite",
    }, {}, response => {
        if (!response) {
            reject(`Background does not answer`);
        }
        if (response.error) {
            reject(response.error);
        } else {
            document.getElementById('connexionMessage').innerHTML = 'You are still connected. WebSite is refreshed !'
            //console.log("Website reloaded");
        }
    });
}

function handleOpenSessionWindow(e) {
    e.preventDefault();
    chrome.runtime.sendMessage({
        kind: "openWindow",
    }, {}, response => {
        if (!response) {
            reject(`Background does not answer`);
        }
        if (response.error) {
            reject(response.error);
        }
    });
}