package main

import (
	"fmt"
	"strings"
	"unicode"

	"code.gitea.io/sdk/gitea"
	"github.com/bbrks/wrap/v2"
)

func GetSeparatorForMultiline() string {
	if config.Language.OpeningOnSeparateLine {
		return "\n"
	}
	return " "
}

func FormatComment(body string, beenWrapped bool) string {
	if beenWrapped && !config.Language.OpeningOnSeparateLine {
		body = " " + strings.TrimPrefix(body, " "+config.Language.Continuation)
	}
	if !beenWrapped && !config.Language.OpeningOnSeparateLine && !strings.HasSuffix(body, "\n") {
		body = body + "\n"
	}
	return fmt.Sprintf("%s%s%s", config.Language.Opening, body, config.Language.Closing)
}

func ProcessComment(wrapper *wrap.Wrapper, comment *gitea.PullReviewComment) {
	body := comment.Body

	beenWrapped := len(body)+len(config.Language.Opening)+len(config.Language.Closing) > 100
	if beenWrapped {
		body = GetSeparatorForMultiline() + wrapper.Wrap(body, 100)
	} else {
		body = " " + body
	}

	body = strings.Replace(body, "\r", "", -1)
	body = strings.Replace(
		body,
		config.Language.Continuation+"\n",
		strings.TrimRightFunc(config.Language.Continuation, unicode.IsSpace)+"\n",
		-1,
	)
	comment.Body = FormatComment(body, beenWrapped)
}

func ProcessComments(splitComments *map[string]([]*gitea.PullReviewComment)) {
	wrapper := wrap.NewWrapper()
	wrapper.OutputLinePrefix = config.Language.Continuation

	for _, comments := range *splitComments {
		for _, comment := range comments {
			ProcessComment(&wrapper, comment)
		}
	}
}