// Package card bouwt Open Graph-kaarten: tekst, SVG en een PNG.
package card

import (
	"bytes"
	"encoding/base64"
	"encoding/xml"
	"fmt"
	"image"
	"image/color"
	_ "image/gif"
	_ "image/jpeg"
	"image/png"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"unicode/utf8"

	"golang.org/x/image/font"
	"golang.org/x/image/font/gofont/gomono"
	"golang.org/x/image/font/gofont/goregular"
	"golang.org/x/image/font/opentype"
	"golang.org/x/image/math/fixed"
)

const (
	Width  = 1200
	Height = 630
	// LockedTitle is de enige tekst op een niet-openbare kaart.
	LockedTitle = "BlueGit – inloggen vereist"
	lockedBody  = "This page is not public."
)

// Meta is wat in de HTML-head en in oEmbed staat.
type Meta struct {
	Title       string
	Description string
	URL         string
	Image       string
	OEmbed      string
	Theme       string
	Kind        string
	Facts       []string
	Initial     string
}

// Render is een kaart plus een optionele avatar (PNG of JPEG).
type Render struct {
	Meta
	Avatar []byte
}

// Blurb is de tekst voor og:description, zonder regeleinden.
func (m Meta) Blurb() string {
	prose := strings.ReplaceAll(m.Description, "\n", " / ")
	prose = strings.Join(strings.Fields(prose), " ")
	facts := strings.Join(m.Facts, " · ")
	if prose == "" {
		return facts
	}
	if facts == "" {
		return prose
	}
	return prose + " · " + facts
}

// Locked is de generieke kaart. url en image mogen geen bronnaam bevatten.
func Locked(pageURL, imageURL, oembed string) Render {
	return Render{Meta: Meta{
		Title: LockedTitle, Description: lockedBody, URL: pageURL, Image: imageURL,
		OEmbed: oembed, Theme: "#142033", Kind: "locked",
	}}
}

// Site is de kaart van BlueGit zelf.
func Site(pageURL, imageURL, oembed string) Render {
	return Render{Meta: Meta{
		Title: "BlueGit", Description: "Git hosting with merge requests, issues and pipelines.",
		URL: pageURL, Image: imageURL, OEmbed: oembed, Theme: "#1f6feb", Kind: "site",
		Initial: "B",
	}}
}

// Excerpt haalt de eerste alinea uit Markdown en kort die in.
// Een kop boven de alinea telt niet mee.
func Excerpt(src string, limit int) string {
	src = fenceRe.ReplaceAllString(src, "\n")
	src = imageRe.ReplaceAllString(src, " ")
	src = linkRe.ReplaceAllString(src, "$1")
	src = htmlRe.ReplaceAllString(src, " ")
	var paras []string
	var cur []string
	flush := func() {
		if len(cur) == 0 {
			return
		}
		text := strings.Join(strings.Fields(cleanLine(strings.Join(cur, " "))), " ")
		cur = nil
		if text != "" {
			paras = append(paras, text)
		}
	}
	for _, line := range strings.Split(src, "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			flush()
			continue
		}
		cur = append(cur, line)
	}
	flush()
	if len(paras) == 0 {
		return ""
	}
	return Clip(paras[0], limit)
}

func cleanLine(s string) string {
	s = strings.TrimLeft(s, ">*-_ ")
	s = strings.ReplaceAll(s, "`", "")
	s = strings.ReplaceAll(s, "*", "")
	s = strings.ReplaceAll(s, "_", "")
	return s
}

// Clip kapt op een runengrens af.
func Clip(s string, limit int) string {
	if limit < 1 || utf8.RuneCountInString(s) <= limit {
		return s
	}
	out := make([]rune, 0, limit)
	for _, r := range s {
		if len(out) == limit-1 {
			break
		}
		out = append(out, r)
	}
	return strings.TrimSpace(string(out)) + "…"
}

var (
	fenceRe = regexp.MustCompile("(?s)```.*?```")
	imageRe = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
	linkRe  = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
	htmlRe  = regexp.MustCompile(`<[^>]+>`)
	lineRe  = regexp.MustCompile(`(?i)^L?(\d+)(?:-(\d+))?$`)
)

// ParseLines leest #L10-20, L10-20 of 10-20. De tweede grens is inclusief.
func ParseLines(token string) (from, to int, ok bool) {
	token = strings.TrimSpace(strings.TrimPrefix(token, "#"))
	m := lineRe.FindStringSubmatch(token)
	if m == nil {
		return 0, 0, false
	}
	from, _ = strconv.Atoi(m[1])
	if from < 1 {
		return 0, 0, false
	}
	to = from
	if m[2] != "" {
		to, _ = strconv.Atoi(m[2])
	}
	if to < from {
		return 0, 0, false
	}
	if to-from > 11 {
		to = from + 11
	}
	return from, to, true
}

// Snippet geeft de gevraagde regels, of anders de eerste regels.
func Snippet(text string, from, to int, withRange bool) string {
	lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
	if len(lines) > 0 && lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	if !withRange {
		from, to = 1, 8
	}
	if from < 1 {
		from = 1
	}
	var out []string
	for n := from; n <= to && n <= len(lines); n++ {
		out = append(out, lines[n-1])
	}
	return strings.Join(out, "\n")
}

// SVG tekent de kaart. Avatar is PNG of JPEG, of leeg.
func SVG(r Render) string {
	theme := r.Theme
	if theme == "" {
		theme = "#1f6feb"
	}
	var b strings.Builder
	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">`)
	b.WriteString(`<rect width="1200" height="630" fill="#071526"/>`)
	fmt.Fprintf(&b, `<rect width="18" height="630" fill="%s"/>`, theme)
	b.WriteString(`<rect x="56" y="48" width="1088" height="534" rx="28" fill="#ffffff"/>`)
	fmt.Fprintf(&b, `<circle cx="150" cy="168" r="52" fill="%s"/>`, theme)
	if len(r.Avatar) > 0 {
		fmt.Fprintf(&b, `<image href="data:image/png;base64,%s" x="98" y="116" width="104" height="104"/>`, base64.StdEncoding.EncodeToString(r.Avatar))
	} else if r.Initial != "" {
		fmt.Fprintf(&b, `<text x="150" y="184" font-size="48" font-family="sans" fill="#ffffff" text-anchor="middle">%s</text>`, xmlText(clipInitial(r.Initial)))
	} else {
		b.WriteString(icon(r.Kind, 128, 144, "#ffffff"))
	}
	fmt.Fprintf(&b, `<text x="224" y="150" font-size="28" font-family="sans" fill="#5c6b80">%s</text>`, xmlText("BlueGit"))
	fmt.Fprintf(&b, `<text x="360" y="150" font-size="28" font-family="sans" fill="%s">%s</text>`, theme, xmlText(kindLabel(r.Kind)))
	y := 214
	for _, line := range wrap(r.Title, 32, 2) {
		fmt.Fprintf(&b, `<text x="224" y="%d" font-size="48" font-family="sans" fill="#142033">%s</text>`, y, xmlText(line))
		y += 58
	}
	descY := 340
	if r.Kind == "file" && strings.Contains(r.Description, "\n") {
		for i, line := range strings.Split(r.Description, "\n") {
			if i == 8 {
				break
			}
			fmt.Fprintf(&b, `<text x="100" y="%d" font-size="26" font-family="mono" fill="#142033">%s</text>`, descY, xmlText(Clip(line, 62)))
			descY += 34
		}
	} else {
		for _, line := range wrap(r.Description, 52, 3) {
			fmt.Fprintf(&b, `<text x="100" y="%d" font-size="30" font-family="sans" fill="#142033">%s</text>`, descY, xmlText(line))
			descY += 42
		}
	}
	fmt.Fprintf(&b, `<text x="100" y="540" font-size="26" font-family="sans" fill="%s">%s</text>`, theme, xmlText(strings.Join(r.Facts, "   ·   ")))
	b.WriteString(`</svg>`)
	return b.String()
}

func kindLabel(kind string) string {
	switch kind {
	case "repository":
		return "Repository"
	case "merge_request":
		return "Merge request"
	case "issue":
		return "Issue"
	case "group":
		return "Group"
	case "user":
		return "User"
	case "commit":
		return "Commit"
	case "pipeline":
		return "Pipeline"
	case "release":
		return "Release"
	case "file":
		return "File"
	case "locked":
		return "Private"
	default:
		return "BlueGit"
	}
}

func icon(kind string, x, y int, fill string) string {
	switch kind {
	case "merge_request":
		return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/>`,
			x+6, y+8, fill, x+22, y+8, fill, x+14, y+28, fill)
	case "issue":
		return fmt.Sprintf(`<circle cx="%d" cy="%d" r="16" fill="none"/><circle cx="%d" cy="%d" r="14" fill="%s"/><circle cx="%d" cy="%d" r="5" fill="#071526"/>`,
			x+18, y+18, x+18, y+18, fill, x+18, y+18)
	case "group":
		return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/><circle cx="%d" cy="%d" r="8" fill="%s"/>`,
			x+6, y+16, fill, x+22, y+16, fill, x+14, y+30, fill)
	case "pipeline":
		return fmt.Sprintf(`<rect x="%d" y="%d" width="8" height="28" rx="2" fill="%s"/><rect x="%d" y="%d" width="8" height="18" rx="2" fill="%s"/><rect x="%d" y="%d" width="8" height="24" rx="2" fill="%s"/>`,
			x+4, y+4, fill, x+16, y+14, fill, x+28, y+8, fill)
	case "release":
		return fmt.Sprintf(`<rect x="%d" y="%d" width="28" height="20" rx="4" fill="%s"/><circle cx="%d" cy="%d" r="4" fill="#071526"/>`,
			x+6, y+10, fill, x+16, y+20)
	case "file":
		return fmt.Sprintf(`<rect x="%d" y="%d" width="26" height="32" rx="3" fill="%s"/>`, x+8, y+4, fill)
	case "locked":
		return fmt.Sprintf(`<circle cx="%d" cy="%d" r="8" fill="none"/><rect x="%d" y="%d" width="22" height="16" rx="3" fill="%s"/><circle cx="%d" cy="%d" r="7" fill="%s"/>`,
			x+18, y+10, x+7, y+16, fill, x+18, y+8, fill)
	default:
		return fmt.Sprintf(`<rect x="%d" y="%d" width="30" height="22" rx="3" fill="%s"/>`, x+6, y+10, fill)
	}
}

func clipInitial(s string) string {
	s = strings.TrimSpace(s)
	if s == "" {
		return ""
	}
	r, _ := utf8.DecodeRuneInString(s)
	return strings.ToUpper(string(r))
}

func wrap(s string, width, max int) []string {
	s = strings.Join(strings.Fields(s), " ")
	if s == "" || max < 1 {
		return nil
	}
	words := strings.Fields(s)
	var lines []string
	var cur string
	for _, w := range words {
		if cur == "" {
			cur = w
			continue
		}
		if utf8.RuneCountInString(cur)+1+utf8.RuneCountInString(w) > width {
			lines = append(lines, cur)
			cur = w
			if len(lines) == max {
				break
			}
			continue
		}
		cur += " " + w
	}
	if len(lines) < max && cur != "" {
		lines = append(lines, cur)
	}
	if len(lines) > max {
		lines = lines[:max]
	}
	return lines
}

func xmlText(s string) string {
	var b bytes.Buffer
	_ = xml.EscapeText(&b, []byte(s))
	return b.String()
}

// PNG rastert de SVG van deze kaart. Alleen de vormen die SVG() schrijft.
func PNG(r Render) ([]byte, error) {
	return Raster(SVG(r))
}

// Raster maakt een PNG van een kaart-SVG.
func Raster(svg string) ([]byte, error) {
	img := image.NewNRGBA(image.Rect(0, 0, Width, Height))
	dec := xml.NewDecoder(strings.NewReader(svg))
	for {
		tok, err := dec.Token()
		if err != nil {
			break
		}
		se, ok := tok.(xml.StartElement)
		if !ok {
			continue
		}
		switch se.Name.Local {
		case "rect":
			fillRound(img, atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "width")), atoi(attr(se, "height")), atoi(attr(se, "rx")), parseColor(attr(se, "fill")))
		case "circle":
			fillCircle(img, atoi(attr(se, "cx")), atoi(attr(se, "cy")), atoi(attr(se, "r")), parseColor(attr(se, "fill")))
		case "image":
			drawDataImage(img, attr(se, "href"), atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "width")), atoi(attr(se, "height")))
		case "text":
			var text string
			for {
				t, err := dec.Token()
				if err != nil {
					break
				}
				if _, ok := t.(xml.EndElement); ok {
					break
				}
				if cd, ok := t.(xml.CharData); ok {
					text += string(cd)
				}
			}
			drawText(img, text, atoi(attr(se, "x")), atoi(attr(se, "y")), atoi(attr(se, "font-size")), attr(se, "font-family"), attr(se, "text-anchor"), parseColor(attr(se, "fill")))
		}
	}
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func attr(se xml.StartElement, name string) string {
	for _, a := range se.Attr {
		if a.Name.Local == name {
			return a.Value
		}
	}
	return ""
}

func atoi(s string) int {
	n, _ := strconv.Atoi(strings.TrimSpace(s))
	return n
}

func parseColor(s string) color.NRGBA {
	s = strings.TrimSpace(s)
	if s == "" || s == "none" {
		return color.NRGBA{}
	}
	s = strings.TrimPrefix(s, "#")
	if len(s) == 3 {
		s = string([]byte{s[0], s[0], s[1], s[1], s[2], s[2]})
	}
	if len(s) != 6 {
		return color.NRGBA{A: 255}
	}
	v, err := strconv.ParseUint(s, 16, 32)
	if err != nil {
		return color.NRGBA{A: 255}
	}
	return color.NRGBA{R: uint8(v >> 16), G: uint8(v >> 8), B: uint8(v), A: 255}
}

func fillRound(img *image.NRGBA, x, y, w, h, rx int, c color.NRGBA) {
	if c.A == 0 || w <= 0 || h <= 0 {
		return
	}
	if rx <= 0 {
		fillRect(img, x, y, w, h, c)
		return
	}
	if rx > w/2 {
		rx = w / 2
	}
	if rx > h/2 {
		rx = h / 2
	}
	fillRect(img, x+rx, y, w-2*rx, h, c)
	fillRect(img, x, y+rx, w, h-2*rx, c)
	fillCircle(img, x+rx, y+rx, rx, c)
	fillCircle(img, x+w-rx, y+rx, rx, c)
	fillCircle(img, x+rx, y+h-rx, rx, c)
	fillCircle(img, x+w-rx, y+h-rx, rx, c)
}

func fillRect(img *image.NRGBA, x, y, w, h int, c color.NRGBA) {
	b := img.Bounds()
	for yy := y; yy < y+h; yy++ {
		if yy < b.Min.Y || yy >= b.Max.Y {
			continue
		}
		for xx := x; xx < x+w; xx++ {
			if xx < b.Min.X || xx >= b.Max.X {
				continue
			}
			img.SetNRGBA(xx, yy, c)
		}
	}
}

func fillCircle(img *image.NRGBA, cx, cy, r int, c color.NRGBA) {
	if c.A == 0 || r <= 0 {
		return
	}
	rr := r * r
	for y := cy - r; y <= cy+r; y++ {
		for x := cx - r; x <= cx+r; x++ {
			dx, dy := x-cx, y-cy
			if dx*dx+dy*dy <= rr {
				if image.Pt(x, y).In(img.Bounds()) {
					img.SetNRGBA(x, y, c)
				}
			}
		}
	}
}

func drawDataImage(img *image.NRGBA, href string, x, y, w, h int) {
	i := strings.Index(href, "base64,")
	if i < 0 || w < 1 || h < 1 {
		return
	}
	raw, err := base64.StdEncoding.DecodeString(href[i+7:])
	if err != nil {
		return
	}
	src, _, err := image.Decode(bytes.NewReader(raw))
	if err != nil {
		return
	}
	sb := src.Bounds()
	rad := w / 2
	for yy := 0; yy < h; yy++ {
		for xx := 0; xx < w; xx++ {
			dx, dy := xx-w/2, yy-h/2
			if dx*dx+dy*dy > rad*rad {
				continue
			}
			sx := sb.Min.X + xx*sb.Dx()/w
			sy := sb.Min.Y + yy*sb.Dy()/h
			c := color.NRGBAModel.Convert(src.At(sx, sy)).(color.NRGBA)
			if c.A == 0 {
				continue
			}
			img.SetNRGBA(x+xx, y+yy, c)
		}
	}
}

func drawText(img *image.NRGBA, text string, x, y, size int, family, anchor string, c color.NRGBA) {
	if text == "" || c.A == 0 || size < 8 {
		return
	}
	face := faceFor(family, size)
	if face == nil {
		return
	}
	d := font.Drawer{Dst: img, Src: image.NewUniform(c), Face: face}
	if anchor == "middle" {
		x -= d.MeasureString(text).Round() / 2
	}
	d.Dot = fixed.P(x, y)
	d.DrawString(text)
}

var (
	faceOnce sync.Once
	sansFont *opentype.Font
	monoFont *opentype.Font
	faceMu   sync.Mutex
	faces    = map[string]font.Face{}
)

func faceFor(family string, size int) font.Face {
	faceOnce.Do(func() {
		sansFont, _ = opentype.Parse(goregular.TTF)
		monoFont, _ = opentype.Parse(gomono.TTF)
	})
	src := sansFont
	if family == "mono" {
		src = monoFont
	}
	if src == nil {
		return nil
	}
	key := family + "/" + strconv.Itoa(size)
	faceMu.Lock()
	defer faceMu.Unlock()
	if f, ok := faces[key]; ok {
		return f
	}
	f, err := opentype.NewFace(src, &opentype.FaceOptions{Size: float64(size), DPI: 72, Hinting: font.HintingNone})
	if err != nil {
		return nil
	}
	faces[key] = f
	return f
}

// Cache bewaart PNG-bytes op de SVG-tekst.
type Cache struct {
	mu    sync.Mutex
	max   int
	order []string
	png   map[string][]byte
	hits  int
}

// NewCache maakt een cache met een maximum aantal kaarten.
func NewCache(max int) *Cache {
	if max < 1 {
		max = 1
	}
	return &Cache{max: max, png: map[string][]byte{}}
}

// Get levert een eerder gerasterde SVG.
func (c *Cache) Get(svg string) ([]byte, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	b, ok := c.png[svg]
	if ok {
		c.hits++
	}
	return b, ok
}

// Put bewaart een PNG.
func (c *Cache) Put(svg string, b []byte) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if _, ok := c.png[svg]; ok {
		c.png[svg] = b
		return
	}
	if len(c.order) >= c.max {
		drop := c.order[0]
		c.order = c.order[1:]
		delete(c.png, drop)
	}
	c.order = append(c.order, svg)
	c.png[svg] = b
}

// Hits telt treffers sinds het starten.
func (c *Cache) Hits() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.hits
}
