package main

import (
	"image"
	"strings"

	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"

	_ "golang.org/x/image/webp"

	"github.com/fogleman/gg"
)

func drawMultilineText(dc *gg.Context, text string, x, y float64, width, lineHeight float64, horizontalAlign, verticalAlign float64) {
	lines := wordWrap(dc, text, width)
	totalHeight := float64(len(lines)) * lineHeight

	// 调整 y 坐标以实现垂直对齐
	y -= totalHeight * verticalAlign

	for _, line := range lines {
		dc.DrawStringAnchored(line, x, y, horizontalAlign, 0)
		y += lineHeight
	}
}

func wordWrap(dc *gg.Context, text string, width float64) []string {
	var lines []string
	words := strings.Fields(text)
	if len(words) == 0 {
		return lines
	}

	var line string
	for _, word := range words {
		testLine := line
		if testLine != "" {
			testLine += " "
		}
		testLine += word

		w, _ := dc.MeasureString(testLine)
		if w > width {
			if line == "" {
				lines = append(lines, word)
			} else {
				lines = append(lines, line)
				line = word
			}
		} else {
			line = testLine
		}
	}

	if line != "" {
		lines = append(lines, line)
	}

	return lines
}

func getLines(text string, width int, fontsize int, chinese bool) (lines int, err error) {
	dc := gg.NewContext(width, 100)
	fontPath := "./en.ttf"
	if chinese {
		fontPath = "./zh.ttf"
	}
	err = dc.LoadFontFace(fontPath, float64(fontsize))
	if err != nil {
		return
	}

	return len(wordWrap(dc, text, float64(width))), nil
}

func drawText(img image.Image, text string, fontsize int, chinese bool) (imgOut *gg.Context, overHeight int, err error) {
	width := img.Bounds().Max.X
	height := img.Bounds().Max.Y
	lines, err := getLines(text, width, fontsize, chinese)
	if err != nil {
		return
	}

	dc := gg.NewContext(width, height+50*lines)
	dc.DrawImage(img, 0, 0)

	// 设置背景颜色
	dc.SetRGB(0, 0, 0) // 黑色背景
	dc.DrawRectangle(0, float64(height), float64(width), float64(50*lines))
	dc.Fill()

	// 加载字体
	fontPath := "./en.ttf"
	if chinese {
		fontPath = "./zh.ttf"
	}
	err = dc.LoadFontFace(fontPath, float64(fontsize))
	if err != nil {
		return
	}
	// 设置文本颜色
	dc.SetRGB(1, 1, 1) // 白色文本

	// 添加文本
	drawMultilineText(dc, text, float64(0), float64(height)+35, float64(width), 50, 0, 0)
	return dc, 50 * lines, nil
}
