package de.kif.backend.util

import com.vladsch.flexmark.ext.autolink.AutolinkExtension
import com.vladsch.flexmark.ext.emoji.EmojiExtension
import com.vladsch.flexmark.ext.emoji.EmojiImageType
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension
import com.vladsch.flexmark.ext.gfm.tasklist.TaskListExtension
import com.vladsch.flexmark.ext.gitlab.GitLabExtension
import com.vladsch.flexmark.ext.tables.TablesExtension
import com.vladsch.flexmark.ext.typographic.TypographicExtension
import com.vladsch.flexmark.ext.youtube.embedded.YouTubeLinkExtension
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.options.MutableDataSet;
import java.util.*

object ParseMarkdown {

    private val parser: Parser
    private val renderer: HtmlRenderer

    fun parse(content: String): String {
        val document = parser.parse(content) ?: return ""
        return renderer.render(document) ?: ""
    }

    init {
        val options = MutableDataSet()

        options.set(
            Parser.EXTENSIONS, Arrays.asList(
                TablesExtension.create(),
                StrikethroughExtension.create(),
                TaskListExtension.create(),
                EmojiExtension.create(),
                AutolinkExtension.create(),
                GitLabExtension.create(),
                TypographicExtension.create(),
                YouTubeLinkExtension.create()
            )
        )

        options.set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_ONLY)

        //options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

        parser = Parser.builder(options).build()
        renderer = HtmlRenderer.builder(options).build()
    }
}

fun markdownToHtml(content: String): String = ParseMarkdown.parse(content)
