package git

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"strings"

	gitea_git "code.gitea.io/gitea/modules/git"
)

func GetSearchBranches(ctx context.Context, repo *gitea_git.Repository, search string, skip, limit int) ([]*gitea_git.Branch, int, error) {
	brs, countAll, err := callShowSearchRef(ctx, repo.Path, gitea_git.BranchPrefix, "--heads", search, skip, limit)
	if err != nil {
		return nil, 0, err
	}
	branches := make([]*gitea_git.Branch, len(brs))
	for i := range brs {
		branches[i] = &gitea_git.Branch{
			Name: brs[i],
			Path: repo.Path,
		}
	}

	return branches, countAll, nil
}

func callShowSearchRef(ctx context.Context, repoPath, prefix, arg, search string, skip, limit int) (branchNames []string, countAll int, err error) {
	stdoutReader, stdoutWriter := io.Pipe()
	defer func() {
		_ = stdoutReader.Close()
		_ = stdoutWriter.Close()
	}()

	go func() {
		stderrBuilder := &strings.Builder{}
		err := gitea_git.NewCommand(ctx, "show-ref").AddDynamicArguments(arg).
			Run(&gitea_git.RunOpts{
				Dir:    repoPath,
				Stdout: stdoutWriter,
				Stderr: stderrBuilder,
			})
		if err != nil {
			if stderrBuilder.Len() == 0 {
				_ = stdoutWriter.Close()
				return
			}
			_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderrBuilder.String()))
		} else {
			_ = stdoutWriter.Close()
		}
	}()

	i := 0
	bufReader := bufio.NewReader(stdoutReader)
	for i < skip {
		line, isPrefix, err := bufReader.ReadLine()
		if err == io.EOF {
			return branchNames, i, nil
		}
		if err != nil {
			return nil, 0, err
		}

		branchName := strings.TrimPrefix(strings.Split(string(line), " ")[1], prefix)
		if len(branchName) > 0 {
			branchName = branchName[:len(branchName)-1]
		}
		isSeached := strings.Contains(branchName, search)

		if !isPrefix && isSeached {
			i++
		}
	}
	for limit == 0 || i < skip+limit {

		branchName, err := bufReader.ReadString('\n')
		if err == io.EOF {
			// This shouldn't happen... but we'll tolerate it for the sake of peace
			return branchNames, i, nil
		}
		if err != nil {
			return nil, i, err
		}
		branchName = strings.TrimPrefix(strings.Split(string(branchName), " ")[1], prefix)
		if len(branchName) > 0 {
			branchName = branchName[:len(branchName)-1]
		}
		isSeached := strings.Contains(branchName, search)
		if isSeached {
			i++
			branchNames = append(branchNames, branchName)
		}
	}
	// count all refs
	for limit != 0 {
		line, isPrefix, err := bufReader.ReadLine()
		if err == io.EOF {
			return branchNames, i, nil
		}
		if err != nil {
			return nil, 0, err
		}

		branchName := strings.TrimPrefix(strings.Split(string(line), " ")[1], prefix)
		if len(branchName) > 0 {
			branchName = branchName[:len(branchName)-1]
		}
		isSeached := strings.Contains(branchName, search)

		if !isPrefix && isSeached {
			i++
		}
	}
	return branchNames, i, nil
}

func ConcatenateError(err error, stderr string) error {
	if len(stderr) == 0 {
		return err
	}
	return fmt.Errorf("%w - %s", err, stderr)
}
