package server

import (
	"testing"

	"gitlab.com/Timfa/bluegit/internal/gitrepo"
)

func TestTreeRowsOpen(t *testing.T) {
	entries := []gitrepo.Entry{
		{Type: "tree", Name: "src"},
		{Type: "tree", Name: "src/pkg"},
		{Type: "blob", Name: "src/main.go"},
		{Type: "blob", Name: "src/pkg/util.go"},
		{Type: "tree", Name: "docs"},
		{Type: "blob", Name: "docs/a.md"},
	}
	rows := treeRows(entries, "src/main.go")
	by := map[string]FileRow{}
	for _, r := range rows {
		by[r.Path] = r
	}
	if !by["src"].Dir || !by["src"].Open || !by["src"].Active || by["src"].Depth != 0 {
		t.Fatalf("src: %+v", by["src"])
	}
	if by["src/pkg"].Open || by["src/pkg"].Active || !by["src/pkg"].Dir {
		t.Fatalf("src/pkg: %+v", by["src/pkg"])
	}
	if by["src/main.go"].Dir || by["src/main.go"].Open || !by["src/main.go"].Active || by["src/main.go"].Depth != 1 {
		t.Fatalf("main: %+v", by["src/main.go"])
	}
	if by["docs"].Open || by["docs"].Active || !by["docs"].Dir {
		t.Fatalf("docs: %+v", by["docs"])
	}
	if by["docs/a.md"].Active || by["docs/a.md"].Open {
		t.Fatalf("a.md: %+v", by["docs/a.md"])
	}

	nested := treeRows(entries, "src/pkg/util.go")
	open := map[string]bool{}
	for _, r := range nested {
		open[r.Path] = r.Open
		if r.Path == "src/pkg/util.go" && (r.Dir || !r.Active || r.Open) {
			t.Fatalf("util: %+v", r)
		}
	}
	if !open["src"] || !open["src/pkg"] || open["docs"] {
		t.Fatalf("voorouders: %v", open)
	}

	folder := treeRows(entries, "docs")
	for _, r := range folder {
		if r.Path == "docs" && (!r.Open || !r.Active) {
			t.Fatalf("docs als huidige map: %+v", r)
		}
		if r.Path == "src" && r.Open {
			t.Fatalf("src hoort dicht: %+v", r)
		}
	}
}
