/*
 * cass_calendar_global - Shortcode for calendar global
 *
 * This shortcode is used to display the calendar global
 */

document.addEventListener('DOMContentLoaded', function () {
    var loader = document.getElementById('cass_shortcode_calendar');
    if (loader) {

        new Vue({
            el: "#cass_shortcode_calendar",
            data: {
                eventRaceSelected: 0,
                races: [],
                races2: [],
                groups: [],
                cancelCourseVisible: false,
                infoCourseVisible: false,
                cancelCourseName: "",
                infoCourseName: "",
                selectedValue: 0
            },
            mounted() {

            },
            created() {
                this.loadData();
            },
            methods: {
                loadInfoCourse() {
                    window.location.href = siteUrl + "/infocourse/?id=" + this.eventRaceSelected + "&returnUrl=" + window.location.href;
                },
                groupFilter() {
                    this.initializeCalendar(this.selectedValue);
                },
                async loadData() {
                    await this.fetchRaceData();
                    await this.fetchGroups();
                },
                async fetchGroups() {
                    const siteUrl = window.siteUrl;
                    siteUrlGroup = siteUrl + "/wp-json/wp-cass/v1/cass-group-list";
                    await axios.get(siteUrlGroup)
                        .then(response => {
                            this.groups = response.data;

                            this.initializeCalendar(window.IDGroup);
                            setTimeout(() => {
                                document.getElementById("cassGroup").selectedIndex = window.IDGroup;
                            }, 5)

                            if(window.viewgroupvisible == 1){
                                document.getElementById("groupFilter").removeAttribute("hidden");
                            }

                        })
                        .catch(error => {
                            console.error('Erreur lors de la récupération de la liste des groupes : ', error);
                        });



                },
                async fetchRaceData() {
                    const adminUrl = window.adminPostUrl;
                    const siteUrl = window.siteUrl;
                    const userID = window.userID;

                    const apiURL = `${siteUrl}/wp-json/wp-cass/v1/cass-race-list`;

                    try {
                        const response = await axios.get(apiURL);
                        this.races = response.data;

                        if (this.races.length != 0) {
                            this.loadCalendar();
                        }

                    } catch (error) {
                        console.error('Erreur Axios :', error);
                    }
                },
                loadCalendar() {
                    // Utilisez la balise script pour inclure le script FullCalendar
                    const script = document.createElement('script');
                    script.src = 'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.9/index.global.js';
                    script.onload = () => {
                        this.initializeCalendar(0);
                    };
                    document.head.appendChild(script);
                },
                async isSignedUp(idRace, oneRace) {

                    const adminUrl = window.adminPostUrl;
                    const siteUrl = window.siteUrl;
                    const userID = window.userID;



                    const apiURL2 = `${siteUrl}/wp-json/wp-cass/v1/cass-member-signedup/${userID}/${idRace}`;

                    try {
                        const response2 = await axios.get(apiURL2);

                        this.races2 = response2.data;

                        var state;

                        this.races2.forEach(race => {
                            state = race.state;
                        })

                        // Controler si excusée, etc...
                        // this.races2.length

                        if (state == 1 || state == 2) {
                            document.getElementById('alreadySignedUp').removeAttribute("hidden");
                            document.getElementById('subscriptionClosed').setAttribute("hidden", "true");
                            document.getElementById('subscription').setAttribute("hidden", "true");
                            document.getElementById('notLoggedIn').setAttribute("hidden", "true");
                        } else {
                            document.getElementById('subscription').removeAttribute("hidden");
                            document.getElementById('alreadySignedUp').setAttribute("hidden", "true");
                            document.getElementById('subscriptionClosed').setAttribute("hidden", "true");
                            document.getElementById('notLoggedIn').setAttribute("hidden", "true");
                        }

                        //Description membre inscrit
                        if (document.getElementById("raceDescriptionMemberSubscribed") != null) {

                            if (state==1 ||state==2) {
                                if (oneRace.descriptionMemberSubscribed == '' || oneRace.descriptionMemberSubscribed == null) {
                                    document.getElementById("raceDescriptionMemberSubscribed").innerHTML = "Il n'y a aucune description pour cette course";
                                } else {
                                    document.getElementById("raceDescriptionMemberSubscribed").innerHTML = ReadGlobal(oneRace.descriptionMemberSubscribed,false);
                                }
                            } else {
                                document.getElementById("raceDescriptionMemberSubscribed").innerHTML = "Vous devez être inscrit pour accéder à ces informations.";
                            }
                        }

                    } catch (error) {
                        console.error('Erreur Axios:', error);
                    }

                },
                initializeCalendar(IDGroup) {

                    let headerToolbarButtons;

                    let buttonText;

                    let isMobile = window.matchMedia("(pointer:coarse)").matches;

                    console.log(isMobile) ;

                    console.log("test") ;

                    if (window.viewChangeVisible == "true") {
                        if(isMobile == true) {
                            headerToolbarButtons="listMonth";
                            window.initialView = "listMonth";
                        }
                        else {
                            headerToolbarButtons = "timeGridDay,timeGridWeek,dayGridMonth,multiMonthYear,listMonth"; }
                    } else {
                        headerToolbarButtons = window.initialView;
                    }

                    var calendarEl = document.getElementById("calendar");

                    var calendar = new FullCalendar.Calendar(calendarEl, {
                        locale: 'fr',
                        firstDay: 1,
                        displayEventTime: false,
                        headerToolbar: {
                            left: "prev,next",
                            center: "title",
                            right: headerToolbarButtons
                        },
                        buttonText: {
                            timeGridDay: 'Jour',
                            timeGridWeek: 'Semaine',
                            dayGridMonth: 'Mois',
                            multiMonthYear: 'Année',
                            listMonth: 'Liste'
                        },
                        titleFormat: isMobile ? {
                            month: 'short',
                            year: 'numeric'
                        } : {
                            month: 'long',
                            year: 'numeric'
                        },
                        initialView: window.initialView,
                        eventMouseEnter: function (event) {
                            $(event.el).popover({
                                trigger: 'manual',
                                title: "<b>" + event.event.title + "</b>",
                                content: '<b>Type : </b>' + event.event.extendedProps.type + '</br><b>Niveau :</b> ' + event.event.extendedProps.level,
                                html: true,
                            }).popover('show');
                        },
                        eventMouseLeave: function (event) {
                            $(event.el).popover('hide');
                        },

                        eventClick: (event) => {
                            document.getElementById("raceDescriptionMemberSubscribed").innerHTML = "";

                            var race = event.event.extendedProps.race;

                            //Matériel
                            //Splitage du matériel

                            var materials;
                            var raceMaterialList = document.getElementById("raceMaterial");

                            // Nettoyer le contenu existant de raceMaterialList
                            raceMaterialList.innerHTML = 'Matériel requis : ';

                            if (race.materials != null) {
                                materials = race.materials.split(',');
                                materials.forEach(material => {
                                    raceMaterialList.innerHTML += '<b>' + ReadGlobal(material, false) + '</b>,';
                                });
                                raceMaterialList.innerHTML = raceMaterialList.innerHTML.slice(0, -1);
                            } else {
                                raceMaterialList.innerHTML = '';
                            }

                            // Description membre
                            if (race.descriptionMemberSubscribed == '') {
                                document.getElementById("raceDescription").innerHTML = "Il n'y a aucune description membre pour cette course";
                            } else {
                                document.getElementById("raceDescription").innerHTML = ReadGlobal(getReturnWithCarriage(race.descriptionMemberSubscribed));
                            }

                            // Description public
                            if (race.descriptionPublic == '' || race.descriptionPublic == null) {
                                document.getElementById("raceDescription").innerHTML = "";
                                document.getElementById("raceDescription").innerHTML = "Il n'y a aucune description pour cette course";
                            } else {
                                document.getElementById("raceDescription").innerHTML = ReadGlobal(race.descriptionPublic, false);
                            }

                            let deputyText = ".";
                            if (race.nameDeputy != null && race.nameDeputy != "")
                                deputyText = " avec comme adjoint <b>" + ReadGlobal(race.nameDeputy, false) + "</b>.";
                            document.getElementById("raceInfo").removeAttribute("hidden");
                            document.getElementById('raceInfo').scrollIntoView();
                            document.getElementById("raceInfo").style.display = "block";
                            document.getElementById('raceName').innerHTML = ReadGlobal(race.name, false);
                            document.getElementById("raceStartEnd").innerHTML = "La course se déroulera du <b>" + getDateFormated(race.start, true) + "</b> au <b>" + getDateFormated(race.end, true) + "</b>";
                            document.getElementById("raceState").innerHTML = "Etat de la course : <b>" + ReadGlobal(getTextFromState(race.state), false) + "</b>";
                            document.getElementById("raceLeader").innerHTML = "La course est géré (chef de course) par <b>" + ReadGlobal(race.nameRL, false) + "</b> " + ReadGlobal(deputyText, false) + "";
                            document.getElementById("raceTypeLevel").innerHTML = "Le type est <b>" + ReadGlobal(race.type, false) + "</b> d'un niveau <b>" + ReadGlobal(race.level, false) + "</b>";
                            document.getElementById("raceGroup").innerHTML = "Groupe : <b>" + ReadGlobal(race.group, false) + "</b>";



                            if(parseInt(race.subscriptionEnable) == 1) {

                                document.getElementById("raceSubscriptionStartEnd").innerHTML = "Les inscriptions sont ouvertes du <b>" + getDateFormated(race.subscriptionStart) + " </b> au <b>" + getDateFormated(race.subscriptionEnd) + "</b>";
                            } else {
                                document.getElementById("raceSubscriptionStartEnd").innerHTML = "Les inscriptions sont ouvertes du <b>" + getDateFormated(race.subscriptionStart) + " </b> au <b>" + getDateFormated(race.subscriptionEnd) + "</b> (actuellement fermées)";
                            }

                            document.getElementById("racePlaceLocality").innerHTML = "La course se déroulera à  <b>"+ReadGlobal(race.placeName,false)+"</b> (<b>"+race.placeLocality+"</b>)";
                            document.getElementById("raceMeeting").innerHTML = "Le lieu de RDV est <b>" + race.meetingPlaceName + "</b>.";
                            document.getElementById("IDRace").value = race.IDRace;
                            document.getElementById("pageUrl").value = window.location;
                            var linkElement = document.getElementById("linkManageUser");
                            if (linkElement) {
                                linkElement.href = siteUrl + "/wp-admin/admin.php?page=cass-admin-race-user-list&action=edit&IDRace=" + race.IDRace;
                            }

                            this.eventRaceSelected = race.IDRace;

                            raceSubscriptionStartEndMeetingPlaceParticipiant = 'Les inscriptions sont ouvertes du <b>' + getDateFormated(race.subscriptionStart) + ' </b> au  <b>' + getDateFormated(race.subscriptionEnd) + '</b>.';
                            if (race.participantMin !== null && race.participantMin !== "" && race.participantMin !== 0) {
                                raceSubscriptionStartEndMeetingPlaceParticipiant += "<br>Le nombre de participant minimum est de <b>" + race.participantMin + "</b>.";
                            }

                            if (race.participantMax !== null && race.participantMax !== "" && race.participantMax !== 0) {
                                raceSubscriptionStartEndMeetingPlaceParticipiant += "<br>Le nombre de participant maximum est de <b>" + race.participantMax + "</b>.";
                            }

                            if (race.meetingPlaceName !== null && race.meetingPlaceName !== "") {
                                raceSubscriptionStartEndMeetingPlaceParticipiant += "<br>Le lieu de RDV est <b>" + race.meetingPlaceName + "</b>.";
                            }



                            document.getElementById("raceSubscriptionStartEndMeetingPlaceParticipiant").innerHTML = ReadGlobal(raceSubscriptionStartEndMeetingPlaceParticipiant,false);


                            //Formulaire d'inscription
                            // Formattage des dates
                            var date = new Date();
                            var today = date.toISOString().slice(0, 19).replace("T", " ");
                            var subscriptionStart = race.subscriptionStart.toLocaleString();
                            var subscriptionEnd = race.subscriptionEnd.toLocaleString();

                            // ContrÃ´le Ã©tat de la course
                            if ((race.state == 2 || race.state == 3) && parseInt(race.subscriptionEnable) == 1) {

                                // ContrÃ´le ouverture des inscriptions
                                var inscriptionElement = document.getElementById('inscription');
                                if (inscriptionElement) {
                                    inscriptionElement.removeAttribute("hidden");
                                }

                                if (today >= subscriptionStart && today <= subscriptionEnd) {
                                    //ContrÃ´ler si c'est un membre connectÃ© ou un visiteur

                                    const userID = window.userID;
                                    if (userID == 0) {
                                        document.getElementById('notLoggedIn').removeAttribute("hidden");
                                        document.getElementById('subscriptionClosed').setAttribute("hidden", "true");
                                        document.getElementById('subscription').setAttribute("hidden", "true");
                                        document.getElementById('alreadySignedUp').setAttribute("hidden", "true");
                                    } else {
                                        this.isSignedUp(race.IDRace, race);
                                    }

                                } else {
                                    document.getElementById('subscriptionClosed').removeAttribute("hidden");
                                    document.getElementById('subscription').setAttribute("hidden", "true");
                                    document.getElementById('alreadySignedUp').setAttribute("hidden", "true");
                                    document.getElementById('notLoggedIn').setAttribute("hidden", "true");
                                }

                            } else {
                                document.getElementById('inscription').setAttribute("hidden", "true");

                            }




                        }
                    });

                    this.races.forEach((race, index) => {
                        if ((race.IDGroup == IDGroup || IDGroup == 0) && race.state != 1) {
                            calendar.addEvent({
                                title: ReadGlobal(race.name, true),
                                id: race.IDRace,
                                start: race.start,
                                end: race.end,
                                type: race.type,
                                level: race.level,
                                extendedProps: { race: race }
                            });
                        }
                    });

                    calendar.render();
                    document.getElementById("progress-bar-container").setAttribute("hidden", "true");
                }


            }

        });
    }
});