{"size": 3983, "ext": "js", "max_stars_repo_path": "public/js/games_table.js", "max_stars_repo_name": "TheFloyds4240/tank-turn-tactics", "max_stars_repo_stars_event_min_datetime": "2021-07-26T08:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:31:23.000Z", "max_issues_repo_path": "public/js/games_table.js", "max_issues_repo_name": "TheFloyds4240/tank-turn-tactics", "max_issues_repo_issues_event_min_datetime": "2021-07-26T08:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T09:15:09.000Z", "max_forks_repo_path": "public/js/games_table.js", "max_forks_repo_name": "TheFloyds4240/tank-turn-tactics", "max_forks_repo_forks_event_min_datetime": "2021-07-24T07:10:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T16:55:54.000Z"}
{"max_stars_count": 2, "max_issues_count": 1, "max_forks_count": 3, "avg_line_length": 29.5037037037, "max_line_length": 110, "alphanum_fraction": 0.5342706503}
const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
    try {
        // Discard the time and time-zone information.
        const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
        const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

        return Math.abs(Math.floor((utc2 - utc1) / _MS_PER_DAY));

    } catch (e) {
        return "?"
    }
}

function formatDate(d) {
    try {
        return `${ d.getFullYear() }-${ d.getMonth() + 1 }-${ d.getDate() }`;
    } catch (e) {
        return d
    }
}

function generateGamesTable(tableQuery, gameObjects) {
    // Generate games table
    const games = gameObjects
    let table = document.querySelector(tableQuery);

    if (table.length) table = table[0];

    const tableHeaders = [ 'Game', 'Players', 'State' ]

    const tableRows = games.map(game => {
        const gameLink = document.createElement("a");
        gameLink.href = "/play?game=" + game._id
        gameLink.innerHTML = game.name;

        let message = 'Day ' + dateDiffInDays(new Date(), new Date(game.startedAt));

        if (!game.hasStarted) {
            message = 'Lobby'
        } else if (game.players.filter(p => p.health > 0).length <= 1) {
            message = 'Finished'
        }

        return [
            gameLink,
            game.players.length,
            message
        ];
    });

    createTable(table, tableHeaders, tableRows)

}

function generateAdminTable(tableQuery) {
    // Generate games table
    fetch('/game/all', { method: 'GET' })
        .then(res => res.json())
        .then(games => {
            let table = document.querySelector(tableQuery);

            const tableHeaders = [ 'Game', 'Players', 'State', 'Creator ID', 'Created', 'Updated', 'Remove' ]

            const tableRows = games.map(game => {
                const gameLink = document.createElement("button");
                gameLink.onclick = () => {
                    console.log(game)
                }
                gameLink.innerHTML = game.name;

                const row = [
                    gameLink,
                    game.players ? game.players.length : "?",
                    game.hasStarted ? 'Day ' + dateDiffInDays(new Date(), new Date(game.startedAt)) : 'Lobby',
                    game.creator_id,
                    formatDate(new Date(game.createdAt)),
                    formatDate(new Date(game.updatedAt)),
                ]

                const deleteButton = document.createElement("button")
                deleteButton.innerHTML = "Delete"

                deleteButton.onclick = function (e) {
                    fetch('/game/' + game._id, { method: 'DELETE' }).then(res => {
                        console.log(res)
                        location.reload()
                    }).catch(err => console.log(err))
                }

                row.push(deleteButton)

                return row;
            });

            createTable(table, tableHeaders, tableRows)
        })
}


function createTable(container, headers, rows) {
    const table = document.createElement("table")

    const tableRow = document.createElement("tr")

    for (let i = 0; i < headers.length; i++) {
        const tableHeader = document.createElement("th")
        tableHeader.innerHTML = headers[i]
        tableRow.appendChild(tableHeader)
    }

    table.appendChild(tableRow)

    for (let i = 0; i < rows.length; i++) {

        const tableRow = document.createElement("tr")

        for (let j = 0; j < headers.length; j++) {
            const tableElement = document.createElement("td");
            if (rows[i][j] instanceof HTMLElement) {
                tableElement.appendChild(rows[i][j])
            } else {
                tableElement.innerHTML = rows[i][j]
            }

            tableRow.appendChild(tableElement)
        }

        table.appendChild(tableRow)
    }

    container.appendChild(table)
}