const elementIdTableListBar = "table-list-bar"
const elementIdTableList = "table-list"
const elementIdTableNameField = "table-name-field"
const elementIdPublicTableCheckbox = "table-public-checkbox"

function setTableListContent(content) {
    document.getElementById(elementIdTableList).innerHTML = content;
}

function getTableName() {
    return document.getElementById(elementIdTableNameField).value
}

function getTableVisibility() {
    return document.getElementById(elementIdPublicTableCheckbox).checked
}

function showAlertWithError(error) {
    window.alert(error.message);
}

function showLoginPage() {
    deleteSessionToken();
    window.location.href = "login.html";
}

function didJoinTable(table, token) {
    console.log("Current table loaded");
    storeTableId(table);
    window.location.href = "play.html";
}

function logoutUser() {
    const token = loadSessionToken();
    if (token == null) {
        showLoginPage();
        return
    }
    performLogoutRequest(token)
    .then(function() {
        showLoginPage();
    }).catch(showAlertWithError)
}

function loadExistingSession() {
    const token = loadSessionToken();
    if (token == null) {
        console.log("No session token, returning to login page");
        showLoginPage();
        return
    }
    console.log(token);
    resumeSessionRequest(token)
    .catch(function(error) {
        console.log("Failed to resume session");
        console.log(error);
        showLoginPage();
    })
    .then(function(name) {
        storePlayerName(name);
        loadCurrentTable(token);
    })
}

function loadCurrentTable(token) {
    performGetCurrentTableRequest(token)
    .then(function(tableId) {
        if (tableId == null) {
            console.log("No table previously joined.");
            refreshTables();
            return;
        }
        didJoinTable(tableId, token);
    })
    .catch(showAlertWithError)
}

function createTable() {
    const tableName = getTableName()
    if (tableName == "") {
        return
    }
    const token = loadSessionToken()
    if (token == null) {
        showLoginPage();
        return;
    }        
    const isVisible = getTableVisibility()
    performCreateTableRequest(token, tableName, isVisible)
    .then(function(tableId) {
        didJoinTable(tableId, token);
    })
    .catch(showAlertWithError)
}

function joinTable(tableId) {
    const token = loadSessionToken()
    if (token == null) {
        showLoginPage();
        return;
    }
    performJoinTableRequest(tableId, token)
    .then(function(tableId) {
        didJoinTable(tableId, token);
    })
    .catch(showAlertWithError)
}

function refreshTables() {
    const token = loadSessionToken();
    if (token == null) {
        console.log("No token to refresh tables");
        showLoginPage();
        return;
    }
    console.log("Refreshing");
    performGetPublicTablesRequest(token)
    .then(processTableList)
    .catch(showAlertWithError)
}

const createTableRow = '<div class="table-row">'
+ '<button class="table-join-btn" onclick="createTable()">Create</button>'
+ '<input type="text" id="table-name-field" name="tablename" placeholder="Create new table..." required>'
+ '<input type="checkbox" id="table-public-checkbox" name="public-table" checked="checked">'
+ '<span id="table-public-label">Public</span>'
+ '</div>'

function processTableList(tables) {
    var html = createTableRow;
    for (let i = 0, len = tables.length; i < len; i++) {
        tableInfo = tables[i]
        html += "<div class=\"table-row\">"
        if (tableInfo.players.length < 4) {
            html += "<button class=\"table-join-btn\" onclick=\"joinTable('" + tableInfo.id + "')\">Join</button>"
        } else {
            html += "<button class=\"table-join-btn\" disabled>Full</button>"
        }
        html += "<div class=\"table-title\">" + tableInfo.name + "</div>"
        if (tableInfo.players.length == 0) {
            html += "<div class=\"table-subtitle\">No players</div>"
        } else {
            const names = tableInfo.players.join(", ")
            html += "<div class=\"table-subtitle\">" + names + "</div>"
        }
        html += "</div>" // table-row 
    }
    setTableListContent(html)
}
