package layouts

import (
	"image"

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

// CoordLayout is a gui.Layout which places its children on predefined coordinates
type CoordLayout struct {
	gui.ViewTmpl
	views map[gui.View]gui.Dimension
}

var _ gui.Layout = &CoordLayout{}

func NewCoordLayout() *CoordLayout {
	return &CoordLayout{
		views: map[gui.View]gui.Dimension{},
	}
}

func (g *CoordLayout) Views() []gui.View {
	s := make([]gui.View, 0, len(g.views))
	for v := range g.views {
		s = append(s, v)
	}
	return s
}

// SetView places v at the given coordinates with the given dimensions.
// v will be added to g's children if not already added before
func (g *CoordLayout) SetView(v gui.View, x, y, width, height int) {
	g.views[v] = gui.Dimension{Point: gui.Point{X: x, Y: y}, Size: gui.Size{Width: width, Height: height}}
}

func (g *CoordLayout) Draw(img *gui.Image, ctx gui.AppContext) {
	for v, d := range g.views {
		v.Draw(img.SubImage(image.Rect(d.X, d.Y, d.Width, d.Height)).(*gui.Image), ctx)
	}
}

func (v *CoordLayout) Layout(ctx gui.AppContext) (prefWidth, prefHeight int) {
	return -1, -1
}

/*
func (g *CoordLayout) OnKeyPressed(event *gui.KeyEvent) (consumed bool) {
	for _, view := range g.Views() {
		if view.OnKeyPressed(event) {
			return true
		}
	}
	return false
}
*/

// TODO OnMouseEvent
