package main

import "math"

// Every ship in the world, connected players and server-run AI alike. The caller
// holds the lock.
func (h *hub) players() []*player {
	players := make([]*player, 0, len(h.clients)+len(h.ai))
	for c := range h.clients {
		players = append(players, c.p)
	}
	return append(players, h.ai...)
}

func (h *hub) body(id int) *body {
	for _, b := range h.bodies {
		if b.ID == id {
			return b
		}
	}
	return nil
}

func (h *hub) player(id int) *player {
	if id == 0 {
		return nil
	}
	for c := range h.clients {
		if c.p.ID == id {
			return c.p
		}
	}
	for _, p := range h.ai {
		if p.ID == id {
			return p
		}
	}
	return nil
}

// A dead or departed ship takes its grudges with it: nobody stays hostile with a
// ship that is no longer there, and no guns stay pointed at a piece that is gone.
func (h *hub) forgive(id int) {
	for _, p := range h.players() {
		if p.Foe == id {
			p.Foe, p.Target = 0, 0
		}
		if p.chase == id {
			p.chase = 0
		}
	}
}

func (h *hub) bodyAt(x, y float64) *body {
	for _, b := range h.bodies {
		if math.Hypot(b.X-x, b.Y-y) < b.R*hitR {
			return b
		}
	}
	return nil
}

func (h *hub) looseByID(id int) *loose {
	for _, l := range h.loose {
		if l.ID == id {
			return l
		}
	}
	return nil
}

// The loose piece under a point, if nobody already has it in hand. Its own outline
// decides, exactly as it is drawn, so a click lands on the piece and never on the
// space around it.
func (h *hub) looseAt(x, y float64) *loose {
	for _, l := range h.loose {
		if l.held == 0 && pieceAt(l.Kind, l.X, l.Y, l.H, x, y) {
			return l
		}
	}
	return nil
}

func (h *hub) oreByID(id int) *ore {
	for _, o := range h.ore {
		if o.ID == id {
			return o
		}
	}
	return nil
}

func (h *hub) removeLoose(id int) {
	for i, l := range h.loose {
		if l.ID == id {
			h.loose = append(h.loose[:i], h.loose[i+1:]...)
			return
		}
	}
}

func (h *hub) removeOre(id int) {
	for i, o := range h.ore {
		if o.ID == id {
			h.ore = append(h.ore[:i], h.ore[i+1:]...)
			return
		}
	}
}
