package client

import (
	"galaxy/client/world"

	"fyne.io/fyne/v2"
)

var m = func(v int) float64 { return float64(v) / float64(world.SCALE) }

func (e *client) onTapped(ev *fyne.PointEvent) {
	if e.world == nil || ev == nil {
		return
	}

	xPx, yPx, ok := e.eventPosToPixel(ev.Position.X, ev.Position.Y)
	if !ok {
		return
	}

	params := e.getLastRenderedParams()
	hits, err := e.world.HitTest(e.hits, &params, xPx, yPx)
	if err != nil {
		e.handlerError(err)
		return
	}

	if len(hits) == 0 {
		e.calculator.UnloadPlanet()
		return
	}

	for i := range hits {
		e.onHit(hits[i])
	}
}

func (e *client) onHit(hit world.Hit) {
	// var coord string
	// if hit.Kind == world.KindLine {
	// 	coord = fmt.Sprintf("{%f,%f - %f,%f}", m(hit.X1), m(hit.Y1), m(hit.X2), m(hit.Y2))
	// } else {
	// 	coord = fmt.Sprintf("{%f,%f}", m(hit.X), m(hit.Y))
	// }
	// fmt.Println("hit:", hit.ID, "Coord:", coord)
	switch hit.Kind {
	case world.KindPoint:
	case world.KindCircle:
		e.onHitCircle(hit.ID)
	case world.KindLine:
	}
}

func (e *client) onHitCircle(id world.PrimitiveID) {
	p, ok := e.reg.localPlanet(id)
	if !ok {
		return
	}
	e.calculator.LoadPlanet(p.Name, p.Number, p.FreeIndustry.F(), p.Material.F(), p.Resources.F())
	e.calculator.Refresh()
}
