package md

import (
	"bytes"
	"errors"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/parser"
)

var PropertyNotFoundError = errors.New("property not found")

func Parse(transformer UrlTransformer, source []byte) (parser.Context, []byte, error) {
	md := goldmark.New(
		goldmark.WithExtensions(
			extension.Footnote, extension.Strikethrough,
			extension.Table,
			&propertiesExtension{},
			&urlTransformerExtension{transformer},
		),
		goldmark.WithRendererOptions(),
	)

	pc := parser.NewContext()
	var readme bytes.Buffer
	err := md.Convert(source, &readme, parser.WithContext(pc))
	if err != nil {
		return nil, nil, err
	}

	return pc, readme.Bytes(), nil
}

func GetProperty(pc parser.Context, key string) (string, error) {
	data := pc.Get(propertiesContextKey)
	if data != nil {
		pData := data.(*propertiesData)
		if pData.Error != nil {
			return "", pData.Error
		}

		value, ok := pData.properties[key]
		if ok {
			return value, nil
		}
	}

	return "", PropertyNotFoundError
}
