package trust_props

import (
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/markup/markdown"
	"reflect"
	"regexp"
)

func SaveRepoAndRenderContent(ctx *context.Context, colName string) (string, error) {
	repo := ctx.Repo.Repository
	toggledContent := ctx.FormString("content")

	content, err := markdown.RenderString(&markup.RenderContext{
		URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
		Metas:     ctx.Repo.Repository.ComposeMetas(),
		GitRepo:   ctx.Repo.GitRepo,
		Ctx:       ctx,
	}, toggledContent)
	if err != nil {
		return "", err
	}

	trimmedToggledContent, err := trimSearchLinks(toggledContent)
	if err != nil {
		return "", err
	}

	fieldNames := map[string]string{
		"resources":   "Resources",
		"competences": "Competences",
	}

	fieldName := fieldNames[colName]
	reflectedRepo := reflect.ValueOf(repo)
	reflectedRepo.Elem().FieldByName(fieldName).SetString(trimmedToggledContent)
	err = repo_model.UpdateRepositoryCols(repo, colName)
	if err != nil {
		return "", err
	}

	return content, nil
}

func trimSearchLinks(content string) (string, error) {
	regExp, err := regexp.Compile(`\s+\[найти\]\(.+\s*\)`)
	if err != nil {
		return "", err
	}
	trimmedSearchLink := regExp.ReplaceAllString(content, "")
	return trimmedSearchLink, nil
}