/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package kr.pe.elex.examples;

import lombok.Getter;
import org.commonmark.Extension;
import org.commonmark.ext.autolink.AutolinkExtension;
import org.commonmark.ext.front.matter.YamlFrontMatterExtension;
import org.commonmark.ext.front.matter.YamlFrontMatterVisitor;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.ext.image.attributes.ImageAttributesExtension;
import org.commonmark.ext.ins.InsExtension;
import org.commonmark.ext.task.list.items.TaskListItemsExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

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

public class CommonMarkdownParser {
	private static final Parser parser;
	private static final HtmlRenderer renderer;

	static {
		final List<Extension> extensions = Arrays.asList(
				TablesExtension.create(),
				AutolinkExtension.create(),
				StrikethroughExtension.create(),
				TablesExtension.create(),
				HeadingAnchorExtension.create(),
				InsExtension.create(),
				YamlFrontMatterExtension.create(),
				ImageAttributesExtension.create(),
				TaskListItemsExtension.create()
		);
		parser = Parser.builder()
				.extensions(extensions)
				.build();
		renderer = HtmlRenderer.builder()
				.extensions(extensions)
				.build();
	}

	//private Node document;
	@Getter
	private String html;
	@Getter
	private Map<String, List<String>> yaml;

	public CommonMarkdownParser() {

	}

	public void parse(final String markdown) {
		final YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
		final Node document = parser.parse(markdown);
		document.accept(visitor);
		this.html = renderer.render(document);
		this.yaml = visitor.getData();
	}


	public static void main(String[] args){
		final String input = "---" +
				"\nlist:" +
				"\n  - value1" +
				"\n  - value2" +
				"\n..." +
				"\n" +
				"\ngreat";
		CommonMarkdownParser p = new CommonMarkdownParser();
		p.parse(input);

		System.out.println(p.getHtml());
		System.out.println(p.getYaml());
	}
}
