package core

import (
	"fmt"
	"strings"
	"unicode"

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

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

func FormatComment(config *Config, body string, beenWrapped bool) string {
	if beenWrapped && !config.Language.OpeningOnSeparateLine {
		body = strings.TrimPrefix(body, config.Language.Continuation)
	}
	body = strings.TrimRightFunc(body, unicode.IsSpace)
	return fmt.Sprintf("%s%s%s", config.Language.Opening, body, config.Language.Closing)
}

func ProcessComment(config *Config, 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(config) + wrapper.Wrap(body, 100)
	}

	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(config, body, beenWrapped)
}

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

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