"use strict";

let db;

// Import ESM into CJS file using immediately invoked function expression because of missing top-level await in CJS
(async () => {
    const { LowSync } = await import('lowdb');
    const { JSONFileSync } = await import('lowdb/node');
    db = new LowSync(new JSONFileSync('db.json'), { teams:  []})
})();

function getTeams() {
    db.read();
    return db.data.teams
}

// Adds passed teamName to db if not already existing
function addTeam(teamName) {
    console.log(teamName)
    db.read();
    if(!db.data.teams.includes(teamName) && teamName != "") {         // Teamname not in db
        db.data.teams.push(teamName);
        db.write();
    } else {                                        // Teamname already in db
    }
}

// Deletes passed teamName from db if existing
function deleteTeam(teamName) {
    db.read();
    if(db.data.teams.includes(teamName) && teamName != "") {         // Teamname in db
        db.data.teams.splice(db.data.teams.indexOf(teamName), 1)       // Delete corresponding array entry
        db.write();
    }
}

// Returns important values from db
function getValues() {
    db.read();
    console.log(db.data)
    return db.data
}

module.exports = {
    getTeams, addTeam, deleteTeam, getValues
}