package filter

import (
	"fmt"
	"strings"

	"gitbase.de/apairon/mark2web/pkg/helper"
	"github.com/flosch/pongo2"
)

// MarkdownFilter is a pongo2 filter, which converts markdown to html
func MarkdownFilter(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
	chromaRenderer := false
	chromaStyle := ""
	if pStr := param.String(); pStr != "" {
		for _, s := range strings.Split(pStr, ",") {
			e := strings.Split(s, "=")
			if len(e) < 2 {
				return nil, &pongo2.Error{
					Sender:    "filter:markdown",
					OrigError: fmt.Errorf("invalid parameter: %s", s),
				}
			}
			switch e[0] {
			case "s":
				if e[1] == "" {
					return nil, &pongo2.Error{
						Sender:    "filter:markdown",
						OrigError: fmt.Errorf("need a syntax sheme name for parameter '%s='", e[0]),
					}
				}
				chromaRenderer = true
				chromaStyle = e[1]
			default:
				return nil, &pongo2.Error{
					Sender:    "filter:markdown",
					OrigError: fmt.Errorf("unknown parameter '%s='", e[0]),
				}
			}

		}
	}
	return pongo2.AsSafeValue(
			string(
				helper.RenderMarkdown(
					[]byte(in.String()),
					chromaRenderer,
					chromaStyle,
				))),
		nil
}
