import { createOrUpdateMspInfo } from "./directus.js"
import { initMap, updateLayers, zoomIn, zoomOut } from "./leaflet.js"

const columns = {
    finessET: 0,
    name: 1,
    name_long: 2,
    dep: 3,
    adresse: 4,
    tel: 5,
    categetab: 6,
    siret: 7,
    x: 8,
    y: 9,
}

let dataCache;
async function getDataP4Pillon() {
    if (dataCache) {
        return dataCache
    }
    const data = await fetch('/data_p4pillon.json')
    dataCache = data.json()
    return dataCache
}
async function getData() {
    const data = await fetch('/data.json')
    return data.json()
}
function getName(msp, dataP4Pillon) {
    return dataP4Pillon ? dataP4Pillon[0] : (msp[columns.name_long] ? msp[columns.name_long] : msp[columns.name])
}

function showInfo() {
    const element = document.getElementById("info")
    element.classList.remove("hidden")
}

function setTitle(title) {
    const elements = document.getElementsByClassName("title")
    for (const element of elements) {
        element.innerHTML = title
    }
}

function setContent(content) {
    const element = document.getElementById("content")
    element.innerHTML = content
}

function setPhone(phone) {
    const element = document.getElementById("phone")
    if (phone) {
        element.href = "tel:" + phone
        element.title = phone
        element.classList.remove('hidden')
    } else {
        element.classList.add('hidden')
    }
}

function setMail(mail) {
    const element = document.getElementById("mail")
    if (mail) {
        element.href = "mailto:" + mail
        element.title = mail
        element.classList.remove('hidden')
    } else {
        element.classList.add('hidden')
    }
}

function setWebsite(website) {
    const element = document.getElementById("website")
    if (website) {
        element.href = website
        element.title = website
        element.classList.remove('hidden')
    } else {
        element.classList.add('hidden')
    }
}

function getContent(msp, dataP4Pillon) {
    return "Établissement FINESS N°" + msp[columns.finessET] +
    (msp[columns.siret] != null ? "<br>SIREN : <a rel='noreferrer' target='_blank' href='https://data.inpi.fr/entreprises/" + msp[columns.siret].substring(0, 9) + "'>" + msp[columns.siret].substring(0, 9) + "</a>" : "") +
    (dataP4Pillon ? "<br>" +
        (dataP4Pillon[1] || dataP4Pillon[2] ? "<br>Leader : " + dataP4Pillon[1] + " " + dataP4Pillon[2] : "") +
        (dataP4Pillon[3] ? "<br>Adhérent à l'association AVEC Santé : ✅" : "") +
        (dataP4Pillon[4] ? "<br>Accord conventionnel interprofessionnel : ✅" : "")
    : "")
}
const editLayoutElement = document.getElementById("editLayout")
function displayInfo(msp, dataP4Pillon) {
    editLayoutElement.classList.add("hidden")
    setTitle(getName(msp, dataP4Pillon))
    setContent(getContent(msp, dataP4Pillon))
    setPhone(msp[columns.tel])
    setMail(msp[columns.mail])
    setWebsite(msp[columns.web])
    showInfo()
}

const layerMSPElement = document.getElementById("layerMSP")
const layerPharmacieElement = document.getElementById("layerPharmacie")

const mspData = {
    nofinesset: document.getElementById("msp-nofinesset"),
    nom: document.getElementById("msp-nom"),
    prenom_leader: document.getElementById("msp-prenom_leader"),
    nom_leader: document.getElementById("msp-nom_leader"),
    avec_sante: document.getElementById("msp-avec_sante"),
    accord_conventionnel_interprofessionnel: document.getElementById("msp-accord_conventionnel_interprofessionnel"),
}

window.displayLayout = async (id) => {
    if (id == "editLayout") {
        const dataP4Pillon = await getDataP4Pillon()
        const msp = window.msp
        const data = dataP4Pillon[msp[columns.finessET]]

        console.log(dataP4Pillon)
        console.log(msp)
        console.log(data)

        mspData.nofinesset.value = window.msp[columns.finessET]
        mspData.nom.value = getName(msp, data)
        mspData.prenom_leader.value = data ? data[1] : ""
        mspData.nom_leader.value = data ? data[2] : ""
        mspData.avec_sante.checked = data ? data[3] : false
        mspData.accord_conventionnel_interprofessionnel.checked = data ? data[4] : false
    }
    document.getElementById(id).classList.remove('hidden')
}

function initZoomBtn() {
    document.getElementById("btnMore").addEventListener('click', () => zoomIn())
    document.getElementById("btnLess").addEventListener('click', () => zoomOut())
}

function initCloseLayoutBtn() {
    [...document.getElementsByClassName("btnClose")].forEach(btnCloseElement => {
        btnCloseElement.addEventListener('click', () => {
            btnCloseElement.parentNode.parentNode.classList.add("hidden")
            console.log(btnCloseElement.parentNode.parentNode.id)
            if (btnCloseElement.parentNode.parentNode.id == "info") {
                editLayoutElement.classList.add("hidden")
            }
        })
    });
}

async function initForms() {
    document.getElementById("formInfo").addEventListener('submit', async (event) => {
        event.preventDefault();

        try {
            const formData = new FormData(event.target)
            const response = await createOrUpdateMspInfo(formData);
            console.log(response)
        } catch (error) {
            console.error(error);
        }
    })
}

async function launchAnnuaire() {
    var data = await getData()
    var dataP4Pillon = await getDataP4Pillon()
    layerMSPElement.addEventListener('change', () => updateLayers(layerMSPElement.checked, layerPharmacieElement.checked));
    layerPharmacieElement.addEventListener('change', () => updateLayers(layerMSPElement.checked, layerPharmacieElement.checked));

    initMap(data, dataP4Pillon, columns, getName, displayInfo, layerMSPElement.checked, layerPharmacieElement.checked)
    initZoomBtn()
    initCloseLayoutBtn()

    initForms()
}

launchAnnuaire()