//= require markdown.converter
//  markdown.editor is slightly adjusted to work with Bootstrap 4.
//  Taken from https://github.com/hughevans/pagedown-bootstrap-rails, V2.1.4
//= require markdown.editor
//= require markdown.sanitizer
//= require markdown.extra

renderPagedown = function() {
    $(".wmd-output").each(function (i) {
        const converter = Markdown.getSanitizingConverter();
        const content = $(this).html();
        return $(this).html(converter.makeHtml(content));
    })
};

createPagedownEditor = function( selector, context ) {
    if (context == null) { context = 'body'; }
    return $(selector, context).each(function(i, input) {
        if ($(input).data('is_rendered')) {
            return;
        }
        const attr = $(input).attr('id').split('wmd-input')[1];
        const converter = Markdown.getSanitizingConverter();
        Markdown.Extra.init(converter);
        const help = {
            handler() {
                window.open('https://daringfireball.net/projects/markdown/syntax', '_blank');
                return false;
            },
            title: "<%= I18n.t('components.markdown_editor.help', default: 'Markdown Editing Help') %>"
        };

        const editor = new Markdown.Editor(converter, attr, help);
        editor.run();
        $('[data-bs-toggle="tooltip"]').tooltip();
        return $(input).data('is_rendered', true);
    });
};

$(document).on('turbolinks:load', function() {
    renderPagedown();
    return createPagedownEditor('.wmd-input');
});
