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

// URL Parameters
const GET = parseURLParameter();

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

/* --- Functions --- */

function loadMarkdownEditor() {
    return new SimpleMDE({
        placeholder: 'Écrire ici ...',
        spellChecker: false,
        toolbar: [
            'bold', 'italic', 'heading', '|', 
            'code', 'quote', 'unordered-list', 'ordered-list', '|', 
            'link', 'image', 'table', '|',
            'preview', 'guide'
        ],
        previewRender: (md) => {
            setTimeout(() => {PR.prettyPrint();}, 250);
            return md.toHTML();
        }
    });
}

function closeWindow() {
    console.log('ici');
    ipcRenderer.send('refresh-card');
    remote.getCurrentWindow().close();
}

function validCard() {
    if ($('#title').val().trim() === '') {
        M.toast({
            html: 'Le titre est vide',
            classes: 'red'
        });
    } else if (init.mdEditor.value().trim() === '') {
        M.toast({
            html: 'Le contenu est vide',
            classes: 'red'
        });
    } else {
        saveCard();
    }
}

function saveCard() {
    const title = $('#title').val();
    const content = init.mdEditor.value()
    // Update
    if (GET.id) {
        DataService.update(GET.id, title, content);
    }
    // Create
    else {
        DataService.add(title, content);
    }
    // Close window
    closeWindow();
}

async function deleteCard() {
    // If update card
    if (GET.id) {
        // Remove card
        const result = await DataService.remove(GET.id);
        if (result) {
            // Close window
            closeWindow();
        }
    }
}