let uniqueID = 0;

let currentActivities = [];

let entryTemplate =
    '<tr class="entry">' +
    '<td class="planning-start"></td>' +
    '<td class="planning-length"></td>' +
    '<td class="planning-name"></td>' +
    '<td class="remove-line">' +
    '<i class="fas fa-trash"></i>' +
    '</td>' +
    '</tr>';

let editEntryTemplate =
    '<label for="startTimeInput">Heure de début</label>\n' +
    '<input type="number" id="startTimeInput">\n' +
    '<label for="lengthTimeInput">Durée</label>\n' +
    '<input type="number" id="lengthTimeInput">\n' +
    '' +
    '<label for="smallTitleInput">Titre dans le planning</label>\n' +
    '<input type="text" id="smallTitleInput">\n' +
    '<label for="fullTitleInput">Titre dans la description</label>\n' +
    '<input type="text" id="fullTitleInput">\n' +
    '' +
    '<label for="descriptionInput">Description</label>\n' +
    '<textarea rows="10" id="descriptionInput"></textarea>' +
    '' +
    '<label for="colorInput">Couleur (hexadécimal)</label>\n' +
    '<input type="text" id="colorInput">\n';

$(document).ready(function () {
    getDayActivities(getSelectedDay());
    $('#daySelect').on('change', function () {
        getDayActivities(getSelectedDay());
    });
    $(".save").click(function () {
        saveDayActivities();
    });
    $('.add-line').on('click', function () {
        let newElem = {};
        uniqueID += 1;
        newElem['ID'] = 'new_'+ uniqueID;
        newElem['day'] = getSelectedDay();
        newElem['start'] = '';
        newElem['length'] = '';
        newElem['small_title'] = '';
        newElem['full_title'] = '';
        newElem['description'] = '';
        currentActivities.push(newElem);
        showInfo(newElem);
        addLine(newElem['ID'], '', '', '');
    });
});

function getSelectedDay() {
    return $('#daySelect').val();
}

function getRealId(id) {
    return id.replace('entry_', '');
}

function findActivityOfId(id) {
    let match = undefined;
    for (let i = 0; i < currentActivities.length; i++) {
        if (currentActivities[i]['ID'] === id) {
            match = currentActivities[i];
            break;
        }
    }
    return match;
}

function removeActivityOfId(id) {
    for (let i = 0; i < currentActivities.length; i++) {
        if (currentActivities[i]['ID'] === id) {
            currentActivities.splice(i, 1);
            break;
        }
    }
}

function updateListEntry(entry) {
    let $listEntry = $('#entry_' + entry['ID']);
    if ($listEntry !== undefined) {
        $listEntry.find('.planning-start').text(entry['start']);
        $listEntry.find('.planning-length').text(entry['length']);
        $listEntry.find('.planning-name').text(entry['small_title']);
    }
}

function addLine(id, start, length, name) {
    let $entry = $(entryTemplate);
    $entry.attr('id', 'entry_' + id);
    $entry.find('.remove-line').attr('id', 'removeEntry_' + id);
    $("#activityTable").prepend($entry);
    $entry.find('.planning-start').text(start);
    $entry.find('.planning-length').text(length);
    $entry.find('.planning-name').text(name);
    $("#removeEntry_" + id).on("click", function () {
        removeActivityOfId(getRealId($entry.attr('id')));
        $entry.remove();
    });
    $entry.on("click", function () {
        showInfo(findActivityOfId(getRealId($entry.attr('id'))));
    });
}

function showInfo(entry) {
    if (entry !== undefined) {
        $.alert({
            title: 'Edition du planning',
            content: editEntryTemplate,
            onOpenBefore: function () {
                $('#startTimeInput').val(entry['start']);
                $('#lengthTimeInput').val(entry['length']);
                $('#smallTitleInput').val(entry['small_title']);
                $('#fullTitleInput').val(entry['full_title']);
                $('#descriptionInput').val(entry['description']);
                $('#colorInput').val(entry['color']);
            },
            onClose: function () {
                entry['start'] =$('#startTimeInput').val();
                entry['length'] = $('#lengthTimeInput').val();
                entry['small_title'] = $('#smallTitleInput').val();
                entry['full_title'] = $('#fullTitleInput').val();
                entry['description'] = $('#descriptionInput').val();
                entry['color'] = $('#colorInput').val();
                updateListEntry(entry);
            },
        });
    } else
        alert('Une erreur est survenue');
}

function saveDayActivities() {
    let object = {
        "function": 'save_day_activities',
        "day": getSelectedDay(),
        "entries": currentActivities,
    };
    $.get(
        "ajax.php",
        object,
        function (data) {
            alert(data);
        });
}

function getDayActivities(day) {
    $('#activityTable').html('');
    let object = {
        "function": 'get_activities_of_day',
        'day': day,
    };
    $.get(
        "../../ajax/read",
        object,
        function (data) {
            currentActivities = data;
            for (let i = 0; i < data.length; i++) {
                addLine(data[i]['ID'], data[i]['start'], data[i]['length'], data[i]['small_title']);
            }
        }
    );
}
