package link.at17.mid.tushare.system.util;

import org.springframework.util.StringUtils;

import com.vladsch.flexmark.util.data.MutableDataSet;
import com.vladsch.flexmark.util.misc.Extension;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.ext.footnotes.FootnoteExtension;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import java.util.Arrays;
import java.util.List;

public class MarkDownUtil {

    public static String postContentToHtml(String postContent) {
        String markDown = mdToHtml(postContent);
        markDown = markDown.replaceAll("class=\"(language-.*?)?\\:n\"", "class=\"line-numbers $1\"");
        return markDown;
    }
    /**
     * 转换md格式为html
     *
     * @param markdownString
     * @return
     */
    public static String mdToHtml(String markdownString) {
        if (!StringUtils.hasText(markdownString)) {
            return "";
        }
        MutableDataSet options = new MutableDataSet();
        List<Extension> extensions = Arrays.asList(
                TablesExtension.create(), 
                FootnoteExtension.create(),
                StrikethroughExtension.create()
                ); 
        options.set(Parser.EXTENSIONS, extensions);
        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        // You can re-use parser and renderer instances
        
        
        Node document = parser.parse(markdownString);
        String html = renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"

        
        
        return html;
         
    }
}
