package main

import (
	"fmt"
	"strings"
	"testing"
)

func TestAlternatives(t *testing.T) {
	pkgProvides := map[string]map[string]bool{
		"kitty":       map[string]bool{"x-terminal-emulator": true},
		"xterm":       map[string]bool{"x-terminal-emulator": true},
		"broken-term": map[string]bool{"x-terminal-emulator": true},
		"sway":        map[string]bool{"x-window-manager": true},
	}
	pkg2files := map[string][]string{
		"kitty": []string{
			"/usr/share/doc/kitty/copyright",
			"/usr/bin/kitty",
		},
		"xterm": []string{
			"/usr/share/doc/xterm/copyright",
			"/usr/bin/xterm",
		},
		"sway": []string{
			"/usr/share/doc/sway/copyright",
			"/usr/bin/sway",
		},
	}

	fakeRunner := func(cmd []string) ([]string, error) {
		// Absence of broken-term here is intentional.
		switch c := strings.Join(cmd, " "); {
		case strings.Contains(c, "--get-selections"):
			return []string{
				"x-terminal-emulator            auto     /usr/bin/xterm",
				"x-terminal-emulator            auto     /usr/bin/kitty",
				"x-window-manager            auto     /usr/bin/sway",
				// A broken entry should be ignored.
				"x-window-manager            auto     ",
				"",
			}, nil
		case strings.Contains(c, "--list x-terminal-emulator"):
			return []string{
				"/usr/bin/kitty",
				"/usr/bin/xterm",
				"",
			}, nil
		case strings.Contains(c, "--list x-window-manager"):
			return []string{
				"/usr/bin/sway",
				"",
			}, nil
		}
		return nil, fmt.Errorf("unexpected arg: %q", cmd)
	}

	got := altChecker{
		uaFunc: fakeRunner,
		emit:   true,
	}.check(pkgProvides, pkg2files)

	want := []altErr{
		{pkg: "broken-term", vpkg: "x-terminal-emulator"},
	}
	if len(want) != len(got) {
		t.Errorf("altChecker().check() =\n%v\nwant: %v", got, want)
	}
}
