let listContainer = $("#dataList");
let displayedItems = [];
let fetchedData = {};

let currentMode = "buy";

let sellClass = 'btn-danger';
let buyClass = 'btn-success';

$(document).ready(async function () {
    await generateList();

    $('#buyButton').addClass(buyClass);
    $('#saveButton').addClass(buyClass);


    $('#buyButton').on('click', function () {
        if (!$(this).hasClass(buyClass)) {
            $(this).addClass(buyClass);
            $('#sellButton').removeClass(sellClass);
            $('#saveButton').removeClass(sellClass).addClass(buyClass);
            currentMode = "buy";
        }
    });
    $('#sellButton').on('click', function () {
        if (!$(this).hasClass(sellClass)) {
            $(this).addClass(sellClass);
            $('#buyButton').removeClass(buyClass);
            $('#saveButton').removeClass(buyClass).addClass(sellClass);
            currentMode = "sell";
        }
    });
    $('#saveButton').on('click', function () {
        let values = getValues();
        let message = 'Voulez vous vraimer ajouter ces articles au stock ?<br><ul>';
        let color = 'green';
        if (currentMode === "sell"){
            message = 'Voulez vous vraiment supprimer ces articles du stock ?<br><ul>';
            color = 'red';
        }
        for (let  i = 0; i < values.length; i++) {
            if (values[i]['value'] > 0){
                message += '<li>' + fetchedData['articles'][i]['name'] + ' : ' + values[i]['value'] + '</li>'
            }
        }
        message += '</ul>';
        $.confirm({
            title: 'Confirmer',
            content: message,
            type: color,
            buttons: {
                formSubmit: {
                    text: 'Confirmer',
                    action: async function () {
                        await AjaxManager.saveStockChange(getFormattedValues(values), currentMode === "sell");
                        await generateList();
                    }
                },
                cancel: {
                    text: 'Annuler',
                }
            }
        });
    });
});

function getListItem(item) {
    const inputId = 'stockDiffInput' + item['id'];
    const labelId = 'stockDiffLabel' + item['id'];
    return (
        '<div class="grid-item">' +
        '<div class="grid-container">' +
        '<div class="img-container">' +
        '<img class="list-image" src="../uploaded_images/' + item['id'] + '.jpg"/>' +
        '</div>' +
        '<h5>' + item['name'] + '</h5>' +
        '<p>Quantité : <strong>' + item['quantity'] + '</strong></p>' +
        '<label for="' + inputId + '" id="' + labelId + '">À Ajouter :</label>' +
        '<input id="' + inputId + '" placeholder="Nombre" type="number" value="0" class="form-control" onchange="onStockDiffInputChange(this)"/>' +
        '</div>' +
        '</div>');
}

function onStockDiffInputChange(input) {
    if ($(input).val() < 0 || isNaN(parseInt($(input).val()))) {
        $(input).val(0);
    }
}


async function generateList() {
    fetchedData = await AjaxManager.getAll();
    displayedItems = [];
    listContainer.html('');
    for (let i = 0; i < fetchedData['articles'].length; i++) {
        let listItem = getListItem(fetchedData['articles'][i]);
        displayedItems.push($(listItem));
        listContainer.append(displayedItems[i]);
    }
}


function getValues() {
    let values = [];
    for (let  i = 0; i < displayedItems.length; i++) {
        let value = displayedItems[i].find('input').val();
        let id = fetchedData['articles'][i]['id'];
        values.push({id: id, value: value});
    }
    return values;
}

function getFormattedValues(values) {
    let newValues = [];
    for (let  i = 0; i < values.length; i++) {
        if (values[i]['value'] > 0)
            newValues.push(values[i]);
    }
    return newValues;
}
