package ui

import (
	"git.solsynth.dev/highland/codingland/pkg/internal/land"
	"github.com/veandco/go-sdl2/sdl"
	"github.com/veandco/go-sdl2/ttf"
	"log"
)

type ButtonObject struct {
	land.BaseUIObject

	Label        string
	Font         *ttf.Font
	OnClickEvent func(mousePos land.Vector2D)
}

func (p *ButtonObject) Draw(pen *sdl.Renderer) {
	var borderWidth int32 = 2

	pen.SetDrawColor(255, 255, 255, 255)
	pen.FillRect(&sdl.Rect{
		X: int32(p.Position.X),
		Y: int32(p.Position.Y),
		W: int32(p.Size.X),
		H: int32(p.Size.Y),
	})
	pen.SetDrawColor(0, 0, 0, 255)
	pen.FillRect(&sdl.Rect{
		X: int32(p.Position.X) + borderWidth/2,
		Y: int32(p.Position.Y) + borderWidth/2,
		W: int32(p.Size.X) - borderWidth,
		H: int32(p.Size.Y) - borderWidth,
	})

	surface, err := p.Font.RenderUTF8Blended(p.Label, sdl.Color{R: 255, G: 255, B: 255, A: 255})
	if err != nil {
		log.Printf("Failed to render text: %s", err)
		return
	}
	defer surface.Free()

	texture, err := pen.CreateTextureFromSurface(surface)
	if err != nil {
		log.Printf("Failed to create texture: %s", err)
		return
	}
	defer texture.Destroy()

	textRect := sdl.Rect{
		X: int32(p.BaseUIObject.Position.X),
		Y: int32(p.BaseUIObject.Position.Y),
		W: surface.W,
		H: surface.H,
	}
	pen.Copy(texture, nil, &textRect)
}

func (p *ButtonObject) OnClick(mousePos land.Vector2D) {
	p.OnClickEvent(mousePos)
}
