const FETCH_OPTIONS = { credentials: 'same-origin' };

function renderContent(element, data) {
    if (!element || !data)
        return;

    if (data.phone_number)
        element.querySelector('[data-id="phone_number"]').textContent = data.phone_number;

    if (data.email && data.email.length)
        element.querySelector('[data-id="email"]').textContent = data.email[0];

    element.dataset.ready = true;
}

function render(element) {
    if (!element || element.dataset.activated)
        return;

    if (element.dataset.objectType !== 'user' || !element.dataset.objectId)
        return;

    let onHover = () => {
        fetch(`/fetch/users/${element.dataset.objectId}/contacts/`, FETCH_OPTIONS)
            .then(res => res.json())
            .then(data => {
                renderContent(element, data);
                element.removeEventListener('mouseenter', onHover);
            })
            .catch(() => {});
    };

    element.addEventListener('mouseenter', onHover);
    element.dataset.activated = true;
}

function renderAll() {
    Array.from(document.querySelectorAll(
        '[data-element="hover_tip"][data-type="contacts"][data-ready="false"]'
    ))
    .forEach(render);
}

renderAll();

export default { render };