package cn.reghao.tnb.search.esapp.blog.util;

import org.commonmark.Extension;
import org.commonmark.ext.front.matter.YamlFrontMatterExtension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.renderer.text.TextContentRenderer;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2023-04-17 04:18:48
 */
public class MarkdownUtil {
    public static String getText(String markdown) {
        Parser parser = Parser.builder()
                .extensions(EXTENSIONS)
                .build();
        Node node = parser.parse(markdown);

        TextContentRenderer textRender = TextContentRenderer.builder().build();
        return textRender.render(node);
    }

    public static String getHtml(String markdown) {
        Parser parser = Parser.builder()
                .extensions(EXTENSIONS)
                .build();
        Node node = parser.parse(markdown);

        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(EXTENSIONS)
                .attributeProviderFactory(context -> new BlogAttributeProvider())
                .build();
        return renderer.render(node);
    }

    private static final List<Extension> EXTENSIONS = Arrays.asList(
            YamlFrontMatterExtension.create(),
            TablesExtension.create()
    );

    static class BlogAttributeProvider implements AttributeProvider {
        @Override
        public void setAttributes(Node node, String s, Map<String, String> map) {
            if (node instanceof TableBlock) {
                map.put("class", "table table-bordered");
            }
        }
    }
}
