package client

import (
	"image/color"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/widget"
)

type interactiveRaster struct {
	widget.BaseWidget

	min        fyne.Size
	raster     *canvas.Raster
	onLayout   func(fyne.Size)
	onScrolled func(*fyne.ScrollEvent)
	onDragged  func(*fyne.DragEvent)
	onDragEnd  func()
	onTapped   func(*fyne.PointEvent)
}

func (r *interactiveRaster) SetMinSize(size fyne.Size) {
	r.min = size
	r.Resize(size)
}

func (r *interactiveRaster) MinSize() fyne.Size {
	return r.min
}

func (r *interactiveRaster) CreateRenderer() fyne.WidgetRenderer {
	return &rasterWidgetRender{
		canvas:   r,
		bg:       canvas.NewRasterWithPixels(bgPattern),
		onLayout: r.onLayout,
	}
}

// Tapped is a left-click event
func (r *interactiveRaster) Tapped(ev *fyne.PointEvent) {
	if r.onTapped == nil {
		return
	}
	r.onTapped(ev)
}

// TappedSecondary is a right-click event
func (r *interactiveRaster) TappedSecondary(*fyne.PointEvent) {}

func newInteractiveRaster(
	raster *canvas.Raster,
	onLayout func(fyne.Size),
	onScrolled func(*fyne.ScrollEvent),
	onDragged func(*fyne.DragEvent),
	onDragEnd func(),
	onTapped func(*fyne.PointEvent),
) *interactiveRaster {
	r := &interactiveRaster{
		raster:     raster,
		onLayout:   onLayout,
		onScrolled: onScrolled,
		onDragged:  onDragged,
		onDragEnd:  onDragEnd,
		onTapped:   onTapped,
	}
	r.ExtendBaseWidget(r)
	return r
}

func bgPattern(x, y, _, _ int) color.Color {
	const boxSize = 25

	if (x/boxSize)%2 == (y/boxSize)%2 {
		return color.Gray{Y: 58}
	}

	return color.Gray{Y: 84}
}

func (r *interactiveRaster) Scrolled(e *fyne.ScrollEvent) {
	if r.onScrolled == nil {
		return
	}
	r.onScrolled(e)
}

func (r *interactiveRaster) Dragged(e *fyne.DragEvent) {
	if r.onDragged == nil {
		return
	}

	r.onDragged(e)
}

func (r *interactiveRaster) DragEnd() {
	if r.onDragEnd == nil {
		return
	}
	r.onDragEnd()
}
