package main

import (
	"math"
	"math/rand"
	"strconv"
)

// An AI hull is a root gun with a few pieces bolted around it. The size says how
// many pieces it carries and the tier how good they are; which piece goes on and
// which slot it lands in is drawn per ship, so two hulls of one size still differ.
// Every kind a player can fly turns up on a hull, because a wreck is the only place
// a piece comes from: a star is the one exception, since being craft-only at the rim
// is all it is.
func (h *hub) compose(size, tier int) []piece {
	ps := []piece{h.fitted("triangle", tier)} // the root gun is what makes it dangerous
	for range size - 1 {
		host := ps[rand.Intn(len(ps))]
		free := freeSlots(ps, host)
		if len(free) == 0 {
			continue // this hull is boxed in, so it just carries less
		}
		q := h.fitted([]string{"triangle", "square", "circle"}[rand.Intn(3)], tier)
		a := float64(free[rand.Intn(len(free))]) / slots * 2 * math.Pi
		q.Parent, q.LX, q.LY = host.ID, host.LX+math.Cos(a)*spacing, host.LY+math.Sin(a)*spacing
		ps = append(ps, q)
	}
	return ps
}

// A police hull: born on a shipyard's ring, it picks an orbit line of its own and
// circles the yard. It is nobody's enemy until someone picks a fight with it.
func (h *hub) spawnAI(b *body) *player {
	a := rand.Float64() * 2 * math.Pi
	r := b.R + standoff
	h.nextID++
	p := &player{ID: h.nextID, Name: "AI" + strconv.Itoa(h.nextID), AI: true, Side: sidePolice, home: b.ID,
		X: b.X + math.Cos(a)*r, Y: b.Y + math.Sin(a)*r,
		angle: a, ring: r + patrolLow + rand.Float64()*patrolHigh,
		spin: patrolSpin * (0.8 + 0.5*rand.Float64())}
	if rand.Intn(2) == 0 {
		p.spin = -p.spin
	}
	p.Pieces = h.compose(aiMin+rand.Intn(aiMax-aiMin+1), 0)
	p.FuelMax = p.capacity()
	p.Fuel = p.FuelMax
	return p
}

// A rogue hull: born on the patrol circle of its point, sized and built by the ring
// it patrols, so the middle ring fields small hulls and the rim fields packs.
func (h *hub) spawnRogue(i int) *player {
	s := h.slots[i]
	n, top := rogueMidPieces+rand.Intn(rogueMidVar), rogueMidTier
	if s.ring >= rimRing-1 {
		n, top = rogueRimPieces+rand.Intn(rogueRimVar), rogueRimTier
	}
	a := rand.Float64() * 2 * math.Pi
	h.nextID++
	p := &player{ID: h.nextID, Name: "ROGUE" + strconv.Itoa(h.nextID), AI: true, Side: sideRogue,
		spot: i, hx: s.x, hy: s.y, angle: a,
		ring: rogueRingLow + rand.Float64()*rogueRingVar,
		spin: patrolSpin * (0.8 + 0.5*rand.Float64())}
	if rand.Intn(2) == 0 {
		p.spin = -p.spin
	}
	p.X, p.Y = s.x+math.Cos(a)*p.ring, s.y+math.Sin(a)*p.ring
	p.H = a
	p.Pieces = h.compose(n, rand.Intn(top+1))
	p.FuelMax = p.capacity()
	p.Fuel = p.FuelMax
	return p
}

// A police hull circles its yard and runs down whoever hit it, and a rogue hull
// watches the gap it was posted in. Both keep to the ground they were given.
func (h *hub) think(p *player, dt float64) {
	if p.Side == sideRogue {
		h.maraud(p, dt)
		return
	}
	p.angle += p.spin * dt
	if p.Foe != 0 {
		p.orbit, p.chase = 0, p.Foe
		return // the chase order below flies it into gun range
	}
	if b := h.body(p.home); b != nil {
		p.TX, p.TY = b.X+math.Cos(p.angle)*p.ring, b.Y+math.Sin(p.angle)*p.ring
	}
}

// A rogue opens fire on anything that is not a rogue the moment it can shoot it, so
// the gun range ring is the whole of its warning. It runs that ship down until one
// of them is dead, but only that far from its own point: every hull flies at the
// same top speed, so a chase with no leash would follow a fleeing player across the
// galaxy forever and break the promise that deep space is not their ground.
func (h *hub) maraud(p *player, dt float64) {
	if o := h.player(p.Foe); o != nil && hostile(p, o) && math.Hypot(o.X-p.hx, o.Y-p.hy) < rogueLeash {
		p.chase = p.Foe
		return // the chase order below flies it into gun range
	}
	p.Foe, p.Target, p.chase = 0, 0, 0 // the prey is gone or out of reach: back to the patrol
	if t := h.prey(p); t != nil {
		p.Foe, p.chase = t.ID, t.ID
		return
	}
	p.angle += p.spin * dt
	p.TX, p.TY = p.hx+math.Cos(p.angle)*p.ring, p.hy+math.Sin(p.angle)*p.ring
}

// The nearest ship a rogue may shoot, which is anything that is not a rogue, and
// only once it is close enough for its own guns: nothing is aggroed from off screen.
func (h *hub) prey(p *player) *player {
	var got *player
	best := gunRange
	for _, o := range h.players() {
		if o == p || !hostile(p, o) {
			continue
		}
		if d := math.Hypot(o.X-p.X, o.Y-p.Y); d < best {
			best, got = d, o
		}
	}
	return got
}

// A wrecked AI leaves its hull in space like anyone else. A yard births a police
// replacement after a delay and a rogue point does the same, so neither runs dry.
func (h *hub) bury(p *player) {
	h.corpse(p)
	for i, q := range h.ai {
		if q == p {
			h.ai = append(h.ai[:i], h.ai[i+1:]...)
			break
		}
	}
	if p.Side == sideRogue {
		h.slots[p.spot].wait = rogueDelay
		return
	}
	h.grave = append(h.grave, &grave{home: p.home, wait: aiDelay})
}

// Graves count down, then birth a new hull in the same shipyard's orbit, and a
// silent rogue point births a new patrol on its own circle.
func (h *hub) stepAI(dt float64) {
	live := h.grave[:0]
	for _, g := range h.grave {
		if g.wait -= dt; g.wait > 0 {
			live = append(live, g)
			continue
		}
		if b := h.body(g.home); b != nil {
			h.ai = append(h.ai, h.spawnAI(b))
		}
	}
	h.grave = live
	for i, s := range h.slots {
		if s.wait <= 0 {
			continue // one is alive and patrolling
		}
		if s.wait -= dt; s.wait > 0 {
			continue
		}
		h.ai = append(h.ai, h.spawnRogue(i))
	}
}
