package main

import (
	"math"
	"math/rand"
)

func oreWait() float64 { return oreWaitMin + rand.Float64()*(oreWaitMax-oreWaitMin) }

// A barren planet throws one ore off its surface every 30-60s, aimed straight
// out, until it holds its full 3-6. The ore coasts out, braking as it goes, and
// parks in a free slot on one of the planet's rings, so no two ore ever overlap.
func (h *hub) spawnOre(b *body) {
	if h.oreCount(b.ID) >= b.cap {
		return // the planet is holding all the ore it will ever hold
	}
	ring, a, ok := h.oreSlot(b)
	if !ok {
		return // no room left in orbit, the planet keeps this one
	}
	o := &ore{ID: h.pieceID(), planet: b.ID, ring: ring, r: b.R + 2, a: a}
	o.vr = math.Sqrt(2 * oreBrake * (ring - o.r)) // just enough to reach the ring
	h.placeOre(o, b)
	h.ore = append(h.ore, o)
}

// A free parking slot: a ring and a slot angle on it, clear of every ore already
// out there. A full planet hands the ore back instead of stacking it.
func (h *hub) oreSlot(b *body) (float64, float64, bool) {
	for i := 0; i < 32; i++ {
		ring := b.R + oreRingMin + float64(rand.Intn(oreRings))*oreGap
		a := rand.Float64() * 2 * math.Pi
		if h.oreClear(b.ID, ring, a) {
			return ring, a, true
		}
	}
	return 0, 0, false
}

// Ore in orbit around a planet, which is what the planet's cap counts. Ore on a
// tow line has left the planet, so hauling some away lets the planet make more.
func (h *hub) oreCount(planet int) int {
	n := 0
	for _, o := range h.ore {
		if o.planet == planet {
			n++
		}
	}
	return n
}

func (h *hub) oreClear(planet int, ring, a float64) bool {
	for _, o := range h.ore {
		if o.planet != planet || math.Abs(o.ring-ring) > 1 {
			continue // a different ring is a different radius, so never a clash
		}
		if math.Abs(wrap(o.a-a))*ring < oreGap {
			return false
		}
	}
	return true
}

func (h *hub) stepOre(o *ore, dt float64) {
	if o.Towed != 0 {
		return // its ship places it
	}
	b := h.body(o.planet)
	if b == nil {
		return // let go in open space, it just drifts where it was dropped
	}
	if o.vr > 0 {
		o.r += o.vr * dt
		o.vr = math.Max(0, o.vr-oreBrake*dt)
		if o.r >= o.ring {
			o.r, o.vr = o.ring, 0 // in orbit now
		}
	}
	h.placeOre(o, b)
}

// An ore never leaves its slot: the whole ring turns instead, so two ore parked on
// one ring stay exactly as far apart as they were placed, forever. The planet's own
// angle is folded in too, so the ring rides around the star with its planet.
func (h *hub) placeOre(o *ore, b *body) {
	a := o.a + (oreOrbitV/o.ring)*h.time + b.a0 + b.speed*h.time
	o.X, o.Y = b.X+math.Cos(a)*o.r, b.Y+math.Sin(a)*o.r
	o.H = a
}

// Ore on a tow line trails straight behind the hull, in the order it was hooked.
func (h *hub) onLine(o *ore, p *player, n float64) {
	d := towGap * n
	o.X, o.Y = p.X-math.Cos(p.H)*d, p.Y-math.Sin(p.H)*d
	o.H = p.H
}
