package renderer

import (
	"strings"

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

// Issuer describes the document issuer.
type Issuer struct {
	LegalName    string `yaml:"legal_name"`
	LegalAddress string `yaml:"legal_address"`
	LogoPath     string `yaml:"logo_path"`
}

func drawHeader(pdf *gofpdf.Fpdf, issuer Issuer, marginLeft, marginTop float64) (float64, error) {
	startX := marginLeft
	startY := marginTop
	logoWidth := 0.0

	if strings.TrimSpace(issuer.LogoPath) != "" {
		logoWidth = 24
		pdf.ImageOptions(issuer.LogoPath, startX, startY, logoWidth, 0, false, gofpdf.ImageOptions{ReadDpi: true}, 0, "")
	}

	textX := startX
	if logoWidth > 0 {
		textX = startX + logoWidth + 6
	}

	pdf.SetXY(textX, startY)
	pdf.SetFont("Helvetica", "B", 12)
	pdf.CellFormat(0, 5, issuer.LegalName, "", 1, "L", false, 0, "")
	pdf.SetX(textX)
	pdf.SetFont("Helvetica", "", 10)
	pdf.MultiCell(0, 4.5, issuer.LegalAddress, "", "L", false)

	if pdf.Error() != nil {
		return 0, pdf.Error()
	}

	currentY := pdf.GetY()

	if logoWidth > 0 {
		logoBottom := startY + logoWidth
		if logoBottom > currentY {
			currentY = logoBottom
		}
	}

	return currentY - startY, nil
}
