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) {
        document.getElementById('connexionMessage').innerHTML = 'Enter Connection 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) {
            document.getElementById('connexionMessage').innerHTML = 'Error, cannot disconnect';
        }
        if (response.error) {
            document.getElementById('connexionMessage').innerHTML = 'Error, cannot disconnect';
        } else {
            renderNotConnected();
            connectionCode = undefined
        }
    });
}

function handleSync(e) {
    e.preventDefault();
    chrome.runtime.sendMessage({
        kind: "reloadWebSite",
    }, {}, response => {
        if (!response) {
            document.getElementById('connexionMessage').innerHTML = 'Error, cannot synchronize';
        }
        if (response.error) {
            document.getElementById('connexionMessage').innerHTML = 'Error, cannot synchronize';
        } 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);
        }
    });
}