package gameui

import (
	"image/color"
	"openquell/assets"

	"github.com/ebitenui/ebitenui/image"
	"github.com/ebitenui/ebitenui/widget"
	"golang.org/x/image/font"
)

func NewMenuButton(text string, fase font.Face, action func(args *widget.ButtonClickedEventArgs)) *widget.Button {
	buttonImage, _ := LoadButtonImage()

	return widget.NewButton(
		widget.ButtonOpts.WidgetOpts(
			widget.WidgetOpts.LayoutData(widget.RowLayoutData{
				Position:  widget.RowLayoutPositionCenter,
				Stretch:   true,
				MaxWidth:  200,
				MaxHeight: 100,
			}),
		),

		widget.ButtonOpts.Image(buttonImage),

		widget.ButtonOpts.Text(text, *assets.FontRenderer.FontNormal, &widget.ButtonTextColor{
			Idle: color.NRGBA{0xdf, 0xf4, 0xff, 0xff},
		}),

		widget.ButtonOpts.TextPadding(widget.Insets{
			Left:   30,
			Right:  30,
			Top:    5,
			Bottom: 5,
		}),

		widget.ButtonOpts.ClickedHandler(action),
	)
}

type RowContainer struct {
	Root *widget.Container
	Row  *widget.Container
}

func (container *RowContainer) AddChild(child widget.PreferredSizeLocateableWidget) {
	container.Row.AddChild(child)
}

func (container *RowContainer) Container() *widget.Container {
	return container.Root
}

// set arg to false if no background needed
func NewRowContainer(setbackground ...bool) *RowContainer {
	background := assets.Assets["background1"]
	var uiContainer *widget.Container

	if len(setbackground) > 0 {
		// false
		uiContainer = widget.NewContainer(
			widget.ContainerOpts.Layout(widget.NewAnchorLayout()),
		)
	} else {
		// default: true
		uiContainer = widget.NewContainer(
			widget.ContainerOpts.BackgroundImage(
				image.NewNineSlice(background, [3]int{0, 1, 639}, [3]int{0, 1, 383})),
			widget.ContainerOpts.Layout(widget.NewAnchorLayout()),
		)
	}

	rowContainer := widget.NewContainer(
		widget.ContainerOpts.WidgetOpts(
			widget.WidgetOpts.LayoutData(widget.AnchorLayoutData{
				HorizontalPosition: widget.AnchorLayoutPositionCenter,
				VerticalPosition:   widget.AnchorLayoutPositionCenter,
			}),
		),
		widget.ContainerOpts.Layout(widget.NewRowLayout(
			widget.RowLayoutOpts.Direction(widget.DirectionVertical),
			widget.RowLayoutOpts.Padding(widget.NewInsetsSimple(20)),
			widget.RowLayoutOpts.Spacing(10),
		)),
	)

	uiContainer.AddChild(rowContainer)

	return &RowContainer{
		Root: uiContainer,
		Row:  rowContainer,
	}
}

func LoadButtonImage() (*widget.ButtonImage, error) {
	idle := image.NewNineSliceColor(color.NRGBA{R: 0x55, G: 0x00, B: 0xe2, A: 255})

	hover := image.NewNineSliceColor(color.NRGBA{R: 130, G: 130, B: 150, A: 255})

	pressed := image.NewNineSliceColor(color.NRGBA{R: 100, G: 100, B: 120, A: 255})

	return &widget.ButtonImage{
		Idle:    idle,
		Hover:   hover,
		Pressed: pressed,
	}, nil
}
