package main

import (
	"opslag.de/schobers/allg5"
	"opslag.de/schobers/geom"
)

type DrawSpriteOptions struct {
	Scale float32
	Tint  *allg5.Color
}

type SpriteDrawer struct {
	ctx *Context
}

func (d SpriteDrawer) scale(sprite, user float32) float32 {
	var scale float32 = 1
	if sprite != 0 {
		scale *= 1 / sprite
	}
	if user != 0 {
		scale *= user
	}
	return scale
}

func (d SpriteDrawer) Draw(name, partName string, pos geom.PointF32, opts DrawSpriteOptions) bool {
	sprite, ok := d.ctx.Sprites[name]
	if !ok {
		return false
	}
	text, ok := d.ctx.Textures[sprite.texture]
	if !ok {
		return false
	}
	partText, ok := text.Subs[partName]
	if !ok {
		return false
	}
	part := sprite.FindPartByName(partName)
	scale := d.scale(part.scale, opts.Scale)
	anchor := part.sub.Min.Sub(part.anchor).ToF32().Mul(scale)
	scrPos := pos.Add(anchor)
	left, top := scrPos.X, scrPos.Y
	var drawOpts allg5.DrawOptions
	if scale != 1 {
		drawOpts.Scale = allg5.NewUniformScale(scale)
	}
	if opts.Tint != nil {
		drawOpts.Tint = opts.Tint
	}
	partText.DrawOptions(left, top, drawOpts)
	return true
}

func (d SpriteDrawer) Size(name, partName string) geom.PointF32 {
	return d.SizeScale(name, partName, 0)
}

func (d SpriteDrawer) SizeScale(name, partName string, scale float32) geom.PointF32 {
	sprite, ok := d.ctx.Sprites[name]
	if !ok {
		return geom.PointF32{}
	}
	part := sprite.FindPartByName(partName)
	scale = d.scale(part.scale, scale)
	return part.sub.Size().ToF32().Mul(scale)
}
