const init = require('./init');

// When document is ready launch js script on the DOM
$(document).ready(() => {init.exec(print)});

// Refresh data when update
ipcRenderer.on('refresh-card', (event, arg) => {
    init.scope.card = DataService.data;
    print(init.scope);
});

/* --- Functions --- */

function print(scope) {
    for(element of scope.card) {
        element.content = element.content.toHTML();
    }
    looper(scope);
    for (cardEdit of $('.card-edit')) {
        const id = $($($(cardEdit).parents()[1]).children()[0]).children()[0].innerHTML;
        $(cardEdit).attr('href', RouteService.path('edit', {id: id}));
    }
    PR.prettyPrint();
}

function saveUserName(input) {
    UserService.username = input.value;
}

function selectCard(card) {
    const id = card.querySelector('[data-val=id]').innerText;
    const data = DataService.getById(id);
    console.log(id, data);
    $('#modal-title').html(data.title);
    $('#modal-content').html(data.content.toHTML())
    $('#modal-delete').attr('data-id', id);
    $('#modal-edit').attr('href', RouteService.path('edit', {id: id}));
    PR.prettyPrint();
    init.modal.open();
}

async function deleteCard(span, fromCard) {
    let card;
    let id;
    // Get id and card element to remove
    if (fromCard) {
        card = $(span).parents();
        id = $($(card[1]).children()[0]).children()[0].innerHTML;
    } else {
        id = $(span).attr('data-id');
        idElements = document.querySelectorAll('[data-val=id]');
        for (idElement of idElements) {
            if (idElement.innerHTML === id) {
                card = $(idElement).parents();
            }
        }
    }
    // Remove data
    const result = await DataService.remove(id);
    if (result) {
        // Remove card on the DOM
        card[2].remove();
        M.toast({
            html: 'Carte supprimée',
        });
    }
}

function exportCard(card, event) {
    // Stop default event
    event.preventDefault();
    // Get card
    const id = $(card).children()[0].innerText;
    // Send info to the main process
    ipcRenderer.send('ondragstart', JSON.parse(localStorage[id]));
}