let uniqueID = 0;

let entryTemplate =
    '<tr class="entry">' +
    '<td class="edit-text"><input class="edit-text-input" type="text" placeholder="Entrez le texte ici"></td>' +
    '<td class="edit-points"><input class="edit-value-input" type="number" value="0"></td>' +
    '<td class="remove-line">' +
    '<i class="fas fa-trash"></i>' +
    '</td>' +
    '</tr>';

$(document).ready(function () {
    getScores(getSelectedTeam());
    setTeamColors(getSelectedTeam());
    $(".add-line").click(function () {
        addLine();
    });
    $(".save").click(function () {
        let lines = getLine();
        let object = {
            "function": 'save_scores',
            "team": getSelectedTeam(),
            "lines": lines,
        };
        $.get(
            'ajax.php',
            object,
            function (data) {
                alert(data);
                window.location.reload();
            });
    });
    $('#teamSelect').on('change', function () {
        getScores(getSelectedTeam());
        setTeamColors(getSelectedTeam());
    });
});

function setTeamColors(team) {
    $('.add-line').attr('id', 'addLine_' + team);
    $('.edit-header').attr('id', 'editHeader_' + team);
}

function getSelectedTeam() {
    return $('#teamSelect').val();
}

function addLine(text, value) {
    uniqueID += 1;
    let $entry = $(entryTemplate);
    $entry.attr('id', 'entry_' + uniqueID);
    $entry.find('.remove-line').attr('id', 'removeEntry_'+uniqueID);
    $(".stats-table").prepend(
        $entry
    );
    $entry.find('.edit-text-input').val(text);
    $entry.find('.edit-value-input').val(value);
    $("#removeEntry_" + uniqueID).on("click", function () {
        $entry.remove();
    });
}

function getLine() {
    let elements = $(".entry").map(function () {
        return this;
    }).get();
    let array = [];
    for (let i = 0; i < elements.length; i++) {
        let values = {
            "text": $(elements[i]).find('.edit-text-input').val(),
            "points": parseInt($(elements[i]).find('.edit-value-input').val())
        };
        array.push(values);
    }
    return array;
}

function getScores(team) {
    $('.stats-table').html('');
    let object = {
        "function": 'get_scores',
        'team': team,
    };
    $.get(
        "../../ajax/read",
        object,
        function (data) {
            for (let i = 0; i < data.length; i++) {
                addLine(data[i]['text'], data[i]['points']);
            }
        }
    );
}
