let ajaxurl = 'ajax/read';


let tableWrapper = $('#tablePlanning');
let cellHeight = 50;
let startHour = 8;

let activityList = [];

let dayNames =
    ['Horaires',
    'Lundi',
    'Mardi',
    'Mercredi',
    'Jeudi',
    'Vendredi',
    'Weekend',];

$(document).ready(function () {
    generateTable();
});

function getDayActivities(day, callback) {
    let object = {
        "function": 'get_activities_of_day',
        'day': day,
    };
    $.get(
        ajaxurl,
        object,
        callback,
    );
}

function getDataOfElement($elem) {
    let id = $elem.attr('id');
    let day = $elem.parent().attr('id').replace('day_', '');
    let data = undefined;
    for (let i = 0; i < activityList[day].length; i++) {
        if (activityList[day][i]['ID'] === id) {
            data = activityList[day][i];
            break;
        }
    }
    return data;
}

function clicked($elem){
    let data = getDataOfElement($elem);
    console.log(data);
    $.alert({
        title: data['full_title'],
        content: data['description'],
    });
}


function generateTable() {
    tableWrapper.html(''); // Reset the table
    generateHours();
    for (let i = 1; i <= 6; i++) { // Iterate over the days
        tableWrapper.append('<div class="day-column" id="day_' + i + '"><div class="planning-header">' + dayNames[i] + '</div></div>');
        let $dayColumn = $('#day_'+i);
        getDayActivities(i, function (data) {
            activityList[i] = data;
            for (let j = 0; j < data.length; j++) {
                addActivityToColumn($dayColumn, data[j]);
            }
        });
    }
}

function addActivityToColumn($col, act) {
    let offsetTop = $col.find('.planning-header').outerHeight(true);
    $col.append('<div class="event ' + act['small_title'] +'" + id="' + act['ID'] +'">' +
        '<div class="event-color">' +
        '<div class="event-text">' +
        act['small_title'] +
        '</div>' +
        '</div>' +
        '</div>');
    let position = (act['start'] - startHour);
    $('#' + act['ID']).css('top', offsetTop +  position * cellHeight);
    $('#' + act['ID']).css('height', act['length'] * cellHeight);
    $('#' + act['ID']).find('.event-color').css('background-color', act['color']);
    $('#' + act['ID']).on('click', function () {
        clicked($(this));
    });
}


function generateHours() {
    tableWrapper.append('<div id="hoursColumn"><div class="planning-header">Horaires</div></div>')
    for (let i = startHour; i < 24; i++) {
        tableWrapper.find('#hoursColumn').append('<div class="horaires">' + i + 'h</div>')
    }
    tableWrapper.find('.horaires').css('height', cellHeight);
}
