const api_url = "https://intra.ffsaf.fr";
//const api_url = "http://localhost:8080";

let map = L.map('map').setView([46.631196, 2.456000], 6);

L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);

const getMeta = async (url) => {
    const img = new Image();
    img.src = url;
    await img.decode();
    return img
};

function timeNumberToSting(nbMin) {
    return String(Math.floor(nbMin / 60)).padStart(2, '0') + ":" + String(nbMin % 60).padStart(2, '0')
}

const sortHoraire = (a, b) => {
    if (a.day === b.day)
        return a.time_start - b.time_start;
    return a.day - b.day;
}

async function getData() {
    const response = await fetch(`${api_url}/api/club/get_map_data`);
    if (!response.ok) {
        throw new Error(`Response status: ${response.status}`);
    }

    const data = await response.json();
    for (const d of data) {
        if (d.training_location.length === 0)
            continue;

        let icon = null;
        if (d.uuid !== null) {
            try {
                const img = await getMeta(`${api_url}/api/club/${d.uuid}/logo`);
                let ratio = img.naturalHeight / img.naturalWidth;

                icon = L.icon({
                    iconUrl: `${api_url}/api/club/${d.uuid}/logo`,

                    iconSize: [50, 50 * ratio], // size of the icon
                    //shadowSize:   [50, 64], // size of the shadow
                    iconAnchor: [25, 50 * ratio], // point of the icon which will correspond to marker's location
                    //shadowAnchor: [4, 62],  // the same for the shadow
                    popupAnchor: [0, -50 * ratio] // point from which the popup should open relative to the iconAnchor
                });
            }catch (e) {
                console.log("Error loading image for club", d.name, e);
            }
        }

        for (const m of d.training_location) {
            let marker;
            if (icon === null)
                marker = L.marker([m.lat, m.lng]);
            else
                marker = L.marker([m.lat, m.lng], {icon: icon});
            marker.addTo(map);

            const div_info = document.createElement("div");
            let tmp = document.createElement("h3");
            tmp.textContent = d.name;
            div_info.appendChild(tmp);

            div_info.appendChild(document.createTextNode(`Adresse: `));
            div_info.appendChild(document.createElement("br"));
            for (const m of d.training_location) {
                div_info.appendChild(document.createTextNode(m.addr));
                div_info.appendChild(document.createElement("br"));
            }
            div_info.appendChild(document.createElement("br"));

            div_info.appendChild(document.createTextNode(`Horaire: `));
            div_info.appendChild(document.createElement("br"));
            if (!d.training_day_time || JSON.parse(d.training_day_time).length === 0) {
                div_info.appendChild(document.createTextNode("Pas d'horaire disponible"));
                div_info.appendChild(document.createElement("br"));
            } else {
                for (const m of JSON.parse(d.training_day_time).sort(sortHoraire)) {
                    let days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"];

                    div_info.appendChild(document.createTextNode(`${days[m.day]}: ${timeNumberToSting(m.time_start)} - ${timeNumberToSting(m.time_end)}`));
                    div_info.appendChild(document.createElement("br"));
                }
            }
            div_info.appendChild(document.createElement("br"));

            div_info.appendChild(document.createTextNode(`Contact: `));
            div_info.appendChild(document.createElement("br"));
            if (d.contact === null || Object.keys(d.contact).length === 0) {
                div_info.appendChild(document.createTextNode("Pas de contact disponible"));
                div_info.appendChild(document.createElement("br"));
            } else {
                for (const [key, value] of Object.entries(d.contact)) {
                    let str

                    if (key === "SITE") {
                        str = document.createElement('a');
                        str.appendChild(document.createTextNode(value))
                        str.title = value
                        str.href = (value.startsWith("http") ? "" : "https://") + value
                        str.target = '_blank'
                    } else if (key === "COURRIEL") {
                        str = document.createElement('a');
                        str.appendChild(document.createTextNode(value))
                        str.title = value
                        str.href = `mailto:${value}`
                        str.target = '_blank'
                    } else if (key === "INSTAGRAM") {
                        let r = value.match(/^https?:\/\/www\.instagram\.com\/([a-zA-Z0-9_.\-]+)\/?$/)
                        str = document.createElement('a');
                        str.appendChild(document.createTextNode(r == null ? value : r[1]))
                        str.title = value
                        str.href = (value.startsWith("http") ? "" : "https://www.instagram.com/") + value
                        str.target = '_blank'
                    } else if (key === "FACEBOOK") {
                        let r = value.match(/^https?:\/\/www\.facebook\.com\/([a-zA-Z0-9_.\-]+)\/?$/)
                        str = document.createElement('a');
                        str.appendChild(document.createTextNode(r == null ? value : r[1]))
                        str.title = value
                        str.href = (value.startsWith("http") ? "" : "https://www.facebook.com/") + value
                        str.target = '_blank'
                    } else {
                        str = document.createTextNode(value)
                    }
                    div_info.appendChild(document.createTextNode(`${key.charAt(0).toUpperCase() + key.slice(1).toLowerCase()}: `));
                    div_info.appendChild(str);
                    div_info.appendChild(document.createElement("br"));
                }
            }
            marker.bindPopup(div_info.innerHTML);

            if (icon !== null) {
                marker.valueOf()._icon.style.backgroundColor = '#FFFFFF';
                marker.valueOf()._icon.style.borderRadius = '10px';
            }
        }
    }
}

getData().then(() => console.log("end loading"));
