package main

import (
	"math"
	"math/rand"
	"sort"
)

// A ring point at angle a, as an offset from the centre of the body's system. The
// body's own place is folded in, so a ship parked there turns with the body around
// the whole star rather than around itself, and systems can sit anywhere.
func ring(b *body, a, r float64) (float64, float64) {
	return b.X - b.cx + math.Cos(a)*r, b.Y - b.cy + math.Sin(a)*r
}

// Parking on a body bolts the target to that body's frame: the ring point turns
// with the planet around its star, so the ship is carried along.
func (h *hub) anchor(p *player, b *body) {
	gap := standoff
	if b.Kind == "star" {
		gap = starGap
	}
	a := math.Atan2(p.Y-b.Y, p.X-b.X) // enter the ring on the side we already are on
	p.orbit, p.anchored = b.ID, h.time
	p.chase = 0 // settling into orbit breaks off any approach order
	p.ox, p.oy = ring(b, a, b.R+gap)
}

// A new run is born on the ring of one of the inner yards, already carried by it:
// a ship starts in orbit, not in empty space.
func (h *hub) deploy(p *player) {
	if len(h.spawns) == 0 {
		return // the generator always yards the core, so there is always somewhere to start
	}
	b := h.body(h.spawns[rand.Intn(len(h.spawns))])
	p.ox, p.oy = ring(b, rand.Float64()*2*math.Pi, b.R+standoff)
	p.X, p.Y = b.cx+p.ox, b.cy+p.oy
	p.TX, p.TY = p.X, p.Y
	p.orbit, p.anchored = b.ID, h.time
}

// Torn-off pieces keep the ids they had, so a piece never becomes a new thing by
// being ripped off a hull.
func (h *hub) detach(p *player, id int) []*loose {
	if len(p.Pieces) < 2 || p.Pieces[0].ID == id {
		return nil
	}
	return h.sever(p, map[int]bool{id: true})
}

// Anything no longer connected to the root piece drifts off, carrying the damage
// it had taken with it.
func (h *hub) sever(p *player, gone map[int]bool) []*loose {
	for grew := true; grew; {
		grew = false
		for _, q := range p.Pieces {
			if !gone[q.ID] && gone[q.Parent] {
				gone[q.ID], grew = true, true
			}
		}
	}
	var off []*loose
	keep := p.Pieces[:0]
	for _, q := range p.Pieces {
		if !gone[q.ID] {
			keep = append(keep, q)
			continue
		}
		off = append(off, h.wreck(p, q))
	}
	p.Pieces = keep
	return off
}

// A piece torn off a hull keeps its identity, its damage and its tier, and lands in
// space where the hull was holding it. A server hull's wreckage carries a timer: it
// is litter from a fight nothing was watching, not somebody's run.
func (h *hub) wreck(p *player, q piece) *loose {
	x, y := hullToWorld(p, q.LX, q.LY)
	l := &loose{ID: q.ID, Kind: q.Kind, X: x, Y: y, H: p.H, HP: q.HP, MaxHP: q.MaxHP, Tier: q.Tier}
	if p.AI {
		l.ttl = wreckTTL
	}
	return l
}

// Wreckage with a timer is taken out of the world when it runs down, unless a hand
// is on it: a piece being dragged is not litter yet. Nothing a player left behind
// has a timer, because that is where a run ended and what it was flying.
func (h *hub) stepLoose(dt float64) {
	live := h.loose[:0]
	for _, l := range h.loose {
		if l.ttl > 0 && l.held == 0 {
			if l.ttl -= dt; l.ttl <= 0 {
				continue
			}
		}
		live = append(live, l)
	}
	h.loose = live
}

// A star is not instant death: its heat eats whatever of the hull actually enters
// it, so brushing the limb costs armour and lingering costs the run. A piece is hit
// by its own outline, not the ship's centre, so a big rig can lose an outer piece
// while the root stays clear.
func (h *hub) burn(p *player, dt float64) {
	var dead []int
	for i := range p.Pieces {
		q := &p.Pieces[i]
		x, y := hullToWorld(p, q.LX, q.LY)
		if !h.hot(x, y) {
			continue
		}
		q.HP = math.Max(0, q.HP-burn*dt)
		if q.HP == 0 {
			dead = append(dead, q.ID)
		}
	}
	for _, id := range dead {
		h.destroy(p, id) // the dead piece and whatever only it held on
	}
}

// A point is hot once it sits past a star's surface, with a piece's own girth
// taken into account, so only real overlap burns.
func (h *hub) hot(x, y float64) bool {
	for _, b := range h.bodies {
		if b.Kind == "star" && math.Hypot(b.X-x, b.Y-y) < b.R+pieceR {
			return true
		}
	}
	return false
}

// A piece at zero hit points is destroyed for good: the hull loses it, and
// whatever it was the only link to breaks off as wreckage.
func (h *hub) destroy(p *player, id int) {
	if len(p.Pieces) < 2 || p.Pieces[0].ID == id {
		return // the root piece is the run itself
	}
	for _, l := range h.sever(p, map[int]bool{id: true}) {
		if l.ID != id {
			h.loose = append(h.loose, l) // the dead piece is gone, not salvage
		}
	}
}

// Losing the root piece ends that life. Everything still bolted to the hull is left
// where the ship died as loose wreckage, the tow line goes slack, and the callsign
// comes back in the core yard's orbit in a brand new ship under a new player id, so
// the client snaps there instead of sliding out of its own corpse.
func (h *hub) respawn(p *player) *player {
	h.corpse(p)
	h.nextID++
	q := &player{ID: h.nextID, Name: p.Name}    // the callsign outlives the ship
	q.Pieces = []piece{h.fitted("triangle", 0)} // every life starts from one triangle
	q.FuelMax = q.capacity()
	q.Fuel = q.FuelMax
	h.deploy(q)
	return q
}

// A dead hull leaves everything but its root piece where it died, its tow line
// goes slack, and the run that just ended is nobody's enemy any more.
func (h *hub) corpse(p *player) {
	h.forgive(p.ID)
	for _, q := range p.Pieces[1:] { // the dead root piece is gone, not salvage
		h.loose = append(h.loose, h.wreck(p, q))
	}
	h.abandon(p)
}

// The slots around a piece that nothing is bolted into yet.
func freeSlots(ps []piece, p piece) []int {
	var free []int
	for i := range slots {
		a := float64(i) / slots * 2 * math.Pi
		x, y := p.LX+math.Cos(a)*spacing, p.LY+math.Sin(a)*spacing
		taken := false
		for _, q := range ps {
			if math.Hypot(q.LX-x, q.LY-y) < spacing*0.5 {
				taken = true
				break
			}
		}
		if !taken {
			free = append(free, i)
		}
	}
	return free
}

// Snap a dropped piece onto the free slot closest to where it was let go.
func (h *hub) attach(p *player, l *loose) bool {
	lx, ly := hullToLocal(p, l.X, l.Y)
	dist := func(q piece) float64 { return math.Hypot(q.LX-lx, q.LY-ly) }
	near := append([]piece(nil), p.Pieces...)
	sort.Slice(near, func(i, j int) bool { return dist(near[i]) < dist(near[j]) })
	if dist(near[0]) > spacing*1.5 {
		return false // not dropped on the hull
	}
	for _, q := range near {
		slot, best := -1, math.MaxFloat64
		for _, i := range freeSlots(p.Pieces, q) {
			a := float64(i) / slots * 2 * math.Pi
			if d := math.Abs(wrap(a - math.Atan2(ly-q.LY, lx-q.LX))); d < best {
				slot, best = i, d
			}
		}
		if slot < 0 {
			continue // piece is surrounded, try the next one out
		}
		a := float64(slot) / slots * 2 * math.Pi
		p.Pieces = append(p.Pieces, piece{
			ID: l.ID, Kind: l.Kind, Parent: q.ID,
			LX: q.LX + math.Cos(a)*spacing,
			LY: q.LY + math.Sin(a)*spacing,
			HP: l.HP, MaxHP: l.MaxHP, Tier: l.Tier,
		})
		h.removeLoose(l.ID)
		return true
	}
	return false
}
