package app

import (
	"strings"
	"testing"
	"time"

	"tobi/internal/session"
)

func TestScrollWindowHoldsTheCursor(t *testing.T) {
	for _, tc := range []struct {
		n, at, avail int
		from, to     int
	}{
		{10, 0, 4, 0, 4},
		{10, 5, 4, 3, 7},
		{10, 9, 4, 6, 10},
		{3, 2, 4, 0, 3},
	} {
		from, to := scrollWindow(tc.n, tc.at, tc.avail)
		if from != tc.from || to != tc.to {
			t.Errorf("scrollWindow(%d, %d, %d) = [%d,%d), want [%d,%d)", tc.n, tc.at, tc.avail, from, to, tc.from, tc.to)
		}
	}
}

func TestViewWindowsLongTablesToTheCursor(t *testing.T) {
	m := pickerModel{width: 80, height: 10, th: newTheme(true)}
	for i := range 30 {
		m.rows = append(m.rows, hostRow{name: "host", probing: true, started: time.Now().Add(-time.Duration(i) * time.Minute)})
	}
	m.rows = append(m.rows, hostRow{name: "zzz", sessions: []session.Session{{ID: "q", Command: "nu", Cwd: "/tmp", StartedAt: time.Now()}}})
	m.cursor = 25
	out := m.view()
	if lines := strings.Count(out, "\n") + 1; lines != m.height {
		t.Errorf("drew %d lines into a %d-line terminal", lines, m.height)
	}
	if !strings.Contains(out, " › host") {
		t.Error("the cursor row is not drawn")
	}
	if !strings.Contains(out, "31 host") {
		t.Error("the header host count is wrong")
	}

	m.cursor = 31 // the session line under the last host
	if !strings.Contains(m.view(), "  ›  q") {
		t.Error("the cursor's session line is not drawn")
	}
}
