package card

import (
	"bytes"
	"image/png"
	"strings"
	"testing"
)

func TestExcerptAndLines(t *testing.T) {
	got := Excerpt("# Titel\n\nEen **widget** die [telt](http://x).\n\nTweede alinea.\n", 80)
	if got != "Een widget die telt." {
		t.Fatalf("excerpt %q", got)
	}
	if !strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "Zichtbaar") || strings.Contains(Excerpt("```\ngeheim\n```\n\nZichtbaar", 40), "geheim") {
		t.Fatal("codeblok")
	}
	from, to, ok := ParseLines("#L10-20")
	if !ok || from != 10 || to != 20 {
		t.Fatalf("bereik %d %d %v", from, to, ok)
	}
	from, to, ok = ParseLines("L4")
	if !ok || from != 4 || to != 4 {
		t.Fatal(from, to)
	}
	lines := make([]string, 25)
	for i := range lines {
		lines[i] = "regel-" + string(rune('a'+i))
	}
	src := strings.Join(lines, "\n") + "\n"
	snip := Snippet(src, 10, 12, true)
	if snip != "regel-j\nregel-k\nregel-l" {
		t.Fatalf("snippet %q", snip)
	}
}

func TestLockedImageOmitsSecret(t *testing.T) {
	secret := "ZXQGEHEIM"
	locked := Locked("https://git.example/", "https://git.example/-/card.png?locked=1", "https://git.example/api/v1/oembed?locked=1")
	svg := SVG(locked)
	if strings.Contains(svg, secret) || !strings.Contains(svg, LockedTitle) {
		t.Fatalf("svg:\n%s", svg)
	}
	pngBytes, err := Raster(svg)
	if err != nil {
		t.Fatal(err)
	}
	cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
	if err != nil || cfg.Width != Width || cfg.Height != Height {
		t.Fatalf("png %v %v", cfg, err)
	}
	pub := locked
	pub.Title = secret
	pub.Description = secret
	pub.Kind = "repository"
	other, err := PNG(pub)
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Equal(pngBytes, other) {
		t.Fatal("verschillende kaarten hebben dezelfde png")
	}
	c := NewCache(2)
	c.Put(svg, pngBytes)
	if _, ok := c.Get(svg); !ok || c.Hits() != 1 {
		t.Fatal("cache")
	}
}

func TestBlurb(t *testing.T) {
	m := Meta{Description: "regel-a\nregel-b", Facts: []string{"Go", "1 star"}}
	if m.Blurb() != "regel-a / regel-b · Go · 1 star" {
		t.Fatalf("blurb %q", m.Blurb())
	}
}
