package routes

import (
	"strings"

	"github.com/jung-kurt/gofpdf"
)

func writePDFTableHeader(pdf *gofpdf.Fpdf, font string, heads []string, widths []float64) {
	pdf.SetFont(font, "B", 5.9)
	pdf.SetFillColor(235, 235, 235)
	for i, h := range heads {
		w := 12.0
		if i < len(widths) {
			w = widths[i]
		}
		pdf.CellFormat(w, 4.8, fitPDFCellText(pdf, h, w-1.2), "1", 0, "L", true, 0, "")
	}
	pdf.Ln(-1)
}

func writePDFTableRow(pdf *gofpdf.Fpdf, cells []string, widths []float64, aligns []string, height float64) {
	for i, c := range cells {
		w := 12.0
		if i < len(widths) {
			w = widths[i]
		}
		align := "L"
		if i < len(aligns) && strings.TrimSpace(aligns[i]) != "" {
			align = aligns[i]
		}
		pdf.CellFormat(w, height, fitPDFCellText(pdf, strings.TrimSpace(c), w-1.2), "1", 0, align, false, 0, "")
	}
	pdf.Ln(-1)
}

func fitPDFCellText(pdf *gofpdf.Fpdf, s string, maxWidth float64) string {
	s = strings.TrimSpace(s)
	if s == "" || pdf.GetStringWidth(s) <= maxWidth {
		return s
	}
	r := []rune(s)
	for len(r) > 0 {
		candidate := string(r) + "..."
		if pdf.GetStringWidth(candidate) <= maxWidth {
			return candidate
		}
		r = r[:len(r)-1]
	}
	return ""
}
