package gitrepo

import (
	"context"
	"strconv"
	"strings"
)

// BranchTip is de punt van een lokale branch.
type BranchTip struct {
	Name, SHA, Subject, Date string
}

// BranchTips geeft elke lokale branch met zijn laatste commit.
func BranchTips(ctx context.Context, gitBin, dir string) ([]BranchTip, error) {
	const format = "%(refname:short)%00%(objectname)%00%(subject)%00%(creatordate:short)"
	out, err := run(ctx, gitBin, nil, "-C", dir, "for-each-ref", "--format="+format, "refs/heads")
	if err != nil {
		return nil, err
	}
	var tips []BranchTip
	for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") {
		if line == "" {
			continue
		}
		parts := strings.Split(line, "\x00")
		if len(parts) < 4 || parts[0] == "" {
			continue
		}
		tips = append(tips, BranchTip{Name: parts[0], SHA: parts[1], Subject: parts[2], Date: parts[3]})
	}
	return tips, nil
}

// AheadBehind telt commits die branch voor en achter base heeft.
// Links in de git-telling is achter, rechts is voor.
func AheadBehind(ctx context.Context, gitBin, dir, base, branch string) (ahead, behind int, err error) {
	out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--left-right", "--count", base+"..."+branch)
	if err != nil {
		return 0, 0, err
	}
	fields := strings.Fields(out)
	if len(fields) != 2 {
		return 0, 0, nil
	}
	behind, _ = strconv.Atoi(fields[0])
	ahead, _ = strconv.Atoi(fields[1])
	return ahead, behind, nil
}

// CreateBranch maakt name op rev. rev is een branch, tag of commit.
func CreateBranch(ctx context.Context, gitBin, dir, name, rev string) error {
	sha, err := run(ctx, gitBin, nil, "-C", dir, "rev-parse", "--verify", "--end-of-options", rev+"^{commit}")
	if err != nil {
		return err
	}
	_, err = run(ctx, gitBin, nil, "-C", dir, "branch", "--", name, strings.TrimSpace(sha))
	return err
}

// DeleteBranch verwijdert een lokale branch.
func DeleteBranch(ctx context.Context, gitBin, dir, name string) error {
	_, err := run(ctx, gitBin, nil, "-C", dir, "branch", "-D", "--", name)
	return err
}

// RenameBranch hernoemt een lokale branch.
func RenameBranch(ctx context.Context, gitBin, dir, oldName, newName string) error {
	_, err := run(ctx, gitBin, nil, "-C", dir, "branch", "-m", "--", oldName, newName)
	return err
}

// ComparePatch is de three-dot diff van from...to, dezelfde vorm als een commit.
func ComparePatch(ctx context.Context, gitBin, dir, from, to string) ([]PatchFile, error) {
	out, err := runAllow(ctx, gitBin, nil, 1, "-c", "core.quotepath=false", "-C", dir, "diff", "--no-color", "--find-renames", "--unified=3", from+"..."+to)
	if err != nil {
		return nil, err
	}
	return ParsePatch(out), nil
}

// Subjects geeft de onderwerpen van rev, nieuwste eerst.
func Subjects(ctx context.Context, gitBin, dir, rev string, limit int) ([]string, error) {
	if limit < 1 {
		limit = 1
	}
	out, err := run(ctx, gitBin, nil, "-C", dir, "log", "--format=%s", "-n", strconv.Itoa(limit), rev)
	if err != nil {
		return nil, err
	}
	var subjects []string
	for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") {
		if line != "" {
			subjects = append(subjects, line)
		}
	}
	return subjects, nil
}
