package views

import (
	"image"

	"git.milar.in/milarin/gui"
)

type AnchorView struct {
	gui.WrapperTmpl
	Anchor gui.Anchor
}

var _ gui.View = &AnchorView{}

func NewAnchorView(view gui.View, anchor gui.Anchor) *AnchorView {
	v := &AnchorView{Anchor: anchor}
	v.SetView(view)
	return v
}

func (v *AnchorView) Draw(img *gui.Image, ctx gui.AppContext) {
	var pos image.Point

	w, h := v.View().Layout(ctx)
	w = iff(w >= 0, w, img.Bounds().Dx())
	h = iff(h >= 0, h, img.Bounds().Dy())

	vw, vh := img.Bounds().Dx(), img.Bounds().Dy()

	switch v.Anchor {
	case gui.AnchorTopLeft:
		pos = image.Pt(0, 0)
	case gui.AnchorTop:
		pos = image.Pt(vw/2-w/2, 0)
	case gui.AnchorTopRight:
		pos = image.Pt(vw-w, 0)
	case gui.AnchorLeft:
		pos = image.Pt(0, vh/2-h/2)
	case gui.AnchorCenter:
		pos = image.Pt(vw/2-w/2, vh/2-h/2)
	case gui.AnchorRight:
		pos = image.Pt(vw-w, vh/2-h/2)
	case gui.AnchorBottomLeft:
		pos = image.Pt(0, vh-h)
	case gui.AnchorBottom:
		pos = image.Pt(0, vh-h)
	case gui.AnchorBottomRight:
		pos = image.Pt(vw-w, vh-h)
	default:
		panic("invalid anchor in AnchorView")
	}

	pos = pos.Add(img.Bounds().Min)
	rect := image.Rect(pos.X, pos.Y, pos.X+w, pos.Y+h)
	v.View().Draw(img.SubImage(rect).(*gui.Image), ctx)
}
