package modules.admin.DocumentCreator.actions;

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlNodeRendererFactory;
import org.commonmark.renderer.html.HtmlRenderer;
import org.skyve.metadata.controller.ServerSideAction;
import org.skyve.metadata.controller.ServerSideActionResult;
import org.skyve.web.WebContext;

import modules.admin.DocumentCreator.SkyveDocumentNodeRenderer;
import modules.admin.domain.DocumentCreator;

public class UpdatePreview implements ServerSideAction<DocumentCreator> {

	private static final long serialVersionUID = -682204740567953097L;

	@Override
	public ServerSideActionResult<DocumentCreator> execute(DocumentCreator bean, WebContext webContext) throws Exception {

		Parser parser = Parser.builder().build();
		Node document = parser.parse(bean.getScript());

		// create a markdown to HTML renderer for the markdown preview tab
		HtmlRenderer htmlRenderer = HtmlRenderer.builder().build();

		// create a markdown to document XML renderer for the document preview tab
		HtmlRenderer documentRenderer = HtmlRenderer.builder().nodeRendererFactory(new HtmlNodeRendererFactory() {
			@Override
			public NodeRenderer create(HtmlNodeRendererContext context) {
				return new SkyveDocumentNodeRenderer(context);
			}
		}).build();

		// update the previews
		bean.setMarkdownPreview(htmlRenderer.render(document));
		bean.setDocumentPreview(documentRenderer.render(document));

		return new ServerSideActionResult<>(bean);
	}

}

@@ -863,17 +863,158 @@
 ption %7B%0A
-%0A
+%09%09String script = bean.getScript();%0A%09%09if (script == null) %7B%0A%09%09%09bean.setMarkdownPreview(null);%0A%09%09%09bean.setDocumentPreview(null);%0A%09%09%7D%0A%09%09else %7B%0A%09
 %09%09Parser
@@ -1051,16 +1051,17 @@
 ld();%0A%09%09
+%09
 Node doc
@@ -1085,28 +1085,20 @@
 rse(
-bean.getS
+s
 cript
-()
 );%0A
-%0A
+%09%0A%09
 %09%09//
@@ -1154,32 +1154,33 @@
 own preview tab%0A
+%09
 %09%09HtmlRenderer h
@@ -1221,25 +1221,27 @@
 ().build();%0A
-%0A
+%09%0A%09
 %09%09// create 
@@ -1305,16 +1305,17 @@
 iew tab%0A
+%09
 %09%09HtmlRe
@@ -1418,16 +1418,17 @@
 () %7B%0A%09%09%09
+%09
 @Overrid
@@ -1429,16 +1429,17 @@
 verride%0A
+%09
 %09%09%09publi
@@ -1499,16 +1499,17 @@
 ) %7B%0A%09%09%09%09
+%09
 return n
@@ -1550,18 +1550,20 @@
 xt);%0A%09%09%09
+%09
 %7D%0A
+%09
 %09%09%7D).bui
@@ -1568,17 +1568,19 @@
 uild();%0A
-%0A
+%09%0A%09
 %09%09// upd
@@ -1596,16 +1596,17 @@
 reviews%0A
+%09
 %09%09bean.s
@@ -1657,16 +1657,17 @@
 nt));%0A%09%09
+%09
 bean.set
@@ -1718,16 +1718,22 @@
 ment));%0A
+%09%09%7D%0A%09%09
 %0A%09%09retur

Fix NPE in DocumentCreator UpdatePreview action.