import './vendor/moment.min';
import './vendor/moment-with-locales.min'

moment.locale('fr');

$( document ).ready(function() {
    var currentDate = moment().locale('fr').format('YYYY-MM-DD');
    var month =  getMonth(currentDate)

    if($('#calendar').length > 0) {
        getEventsForMonth(allEvents, month)
    }

    $('#previous').on('click', function(e){
        var tmp = currentDate.split("-");
        if(tmp[1] == '01'){
            tmp[1] = '12'
            tmp[0] = parseInt(tmp[0])-1
        }else{
            tmp[1] = parseInt(tmp[1])-1
        }

        if(tmp[1] < 10 && tmp[1] !== "01"){
            tmp[1] = ('0' + tmp[1] )
        }

        tmp[2] = 15;
        var newDate = tmp.join('-')
        month = getMonth(newDate)
        currentDate = newDate

        getEventsForMonth(allEvents, month)
    })

    $("#next").on("click", function(e){
        var tmp = currentDate.split("-");

        if (tmp[1] == '12') {
            tmp[1] = '01'
            tmp[0] = parseInt(tmp[0])+1
        } else {
            tmp[1] = parseInt(tmp[1])+1
        }

        if (tmp[1] < 10 && tmp[1] !== "01") {
            tmp[1] = ('0' + tmp[1] )
        }

        tmp[2] = 15
        var newDate = tmp.join('-')
        month = getMonth(newDate)
        currentDate = newDate
        getEventsForMonth(allEvents,month)
    })

    function getMonth(date){
        $('#month').html("");
        let mois = moment(date).locale('fr').format('MMMM');
        let moisCapitalise = mois.charAt(0).toUpperCase() + mois.slice(1)
        $('#month').append(moisCapitalise+' '+moment(date).locale('fr').format('YYYY'));

        var month = {
            start: parseInt(moment(date).startOf('month').format('X')),
            end: parseInt(moment(date).endOf('month').format('X'))
        };

        return month;
    }

    function getEventsForMonth(events, monthConcerned){
        $('.calendarbody').addClass('d-none');
        $('.calendarbody').html("")
        let eventsInThisMonth = []

        for (var i = 0; i<events.length; i++) {
            if (events[i].start < monthConcerned.end && events[i].end > monthConcerned.start) {
                eventsInThisMonth.push(events[i])
            }
        }

        if (eventsInThisMonth.length == 0) {
            $('.calendarbody').append(`<div class="alert alert-info"><p> Aucun événement </p></div>`);
        }

        for (var j = 0; j < eventsInThisMonth.length; j++) {
            var dateMomentStart = moment(eventsInThisMonth[j].start, "X").locale('fr')
            var dateMomentEnd = moment(eventsInThisMonth[j].end, "X").locale('fr')
            var dateDeb = moment(eventsInThisMonth[j].start, "X").locale('fr').format('DD MMM HH:mm')
            var dateFin = moment(eventsInThisMonth[j].end, "X").locale('fr').format('DD MMM HH:mm')
            var dateEve = "";

            if(dateMomentStart.format('DD MMM') == dateMomentEnd.format('DD MMM') && dateMomentStart.format('HH:mm') == "00:00" && dateMomentEnd.format('HH:mm') == "23:59"){
                dateEve = `Le ${dateMomentStart.format('DD MMMM YYYY')}`;
            } else if(dateMomentStart.format('HH:mm') == "00:00" && dateMomentEnd.format('HH:mm') == "23:59"){
                dateEve = `Du ${dateMomentStart.format('DD MMMM YYYY')} au ${dateMomentEnd.format('DD MMMM YYYY')}`;
            } else if (dateMomentStart.format('DD MMM') == dateMomentEnd.format('DD MMM')){
                dateEve = `Le ${dateMomentStart.format('DD MMMM YYYY HH:mm')} - ${dateMomentEnd.format('HH:mm')}`;
            } else {
                dateEve = `Du ${dateMomentStart.format('DD MMMM YYYY HH:mm')} au ${dateMomentEnd.format('DD MMMM YYYY HH:mm')}`;
            }

            var title = eventsInThisMonth[j].title
            var content = eventsInThisMonth[j].content
            var id = eventsInThisMonth[j].id
            var typeActu = eventsInThisMonth[j].type_actu
            var image = eventsInThisMonth[j].image
            var link = eventsInThisMonth[j].link
            var style = image != '' ? `style = 'background-image : url(/photos/actus/${image})'` : `style = 'background-image : url(/photos/actus/agenda-default.jpg)'`;
            var titleClass = "title";
            var card = `
                <div class="col-sm-6 well mb-3 actu_${typeActu}">
                    <a class="linkActu" href="${link}" target="_blank">
                        <div class="event" data-id="${id}">
                            <div class="titlebkg" ${style}><h3 class="${titleClass}"> ${title}</h3></div>
                            <div class="date-agenda ${typeActu}" ><span class="icon-calendar"></span> ${dateEve}</div>
                            <p class="accroche">${content}</p>
                        </div>
                    </a>
                </div>
                `;
            if (j == 0)
                $('.calendarbody').append('<div class="row">'+ card)
            else
                $('.calendarbody .row:last').append(card+'</div>')
        }
        $('.calendarbody').append('</div>');
        if ($('.calendar-ko2m').length != 0) {
            document.querySelectorAll('.calendarbody .col-sm-6').forEach(el => {
                el.classList.remove('col-sm-6', 'well');
                el.classList.add('col-6', 'col-sm-4', 'col-md-3');
            });
            $('.alert.alert-info').each(function () {
                const $alert = $(this);

                // Modifier les classes de l'alerte
                $alert
                    .removeClass('alert alert-info')
                    .addClass('rounded-3 bg-light-50 p-3 text-center');

                // Ajouter mb-0 au <p> contenu à l’intérieur
                $alert.find('p').addClass('mb-0');
            });

            $('.event').each(function() {
                const $accroche = $(this).find('.accroche');
                const $date = $(this).find('.date-agenda');
                const $h3 = $(this).find('.titlebkg h3');
                const $titleBkg = $(this).find('.titlebkg');

                if ($accroche.length && $h3.length) {
                    $accroche.insertAfter($titleBkg);
                    $h3.insertAfter($titleBkg);
                }
                if ($date.length && $h3.length && $accroche.length) {
                    const $wrapper = $('<div class="p-3"></div>');
                    $date.before($wrapper);
                    $wrapper.append($date, $h3, $accroche);
                }
                $h3.addClass('h5 mb-0');
                $accroche.addClass('mb-0');
            });

            $('.linkActu').each(function () {
                const $link = $(this);
                const href = $link.attr('href');
                const target = $link.attr('target');
                const $event = $link.find('.event');

                const $h3 = $event.find('h3.title');
                const titleText = $h3.text().trim();
                const $date = $event.find('.date-agenda');

                const $newLink = $('<a></a>')
                    .addClass('linkActu stretched-link')
                    .attr('href', href)
                    .attr('target', target)
                    .text(titleText);

                $h3.empty().append($newLink);

                if ($date.length) {
                    $date.wrap('<small></small>');
                    $h3.after($date.parent());
                }

                $link.replaceWith($event);
            });
        }
        $('.calendarbody').removeClass('d-none');
    }
});
