package main

import (
	"encoding/json"
	"math"
	"time"

	"github.com/gorilla/websocket"
)

// The rig flies as one body: steer toward the target, never past it. A target that
// moves carries its own velocity, and the ship flies that plus its closing speed, so
// the slowdown ramp measures the gap that is left and not a point that runs away.
func (p *player) steer(dt, tvx, tvy float64) {
	dx, dy := p.TX-p.X, p.TY-p.Y
	dist := math.Hypot(dx, dy)
	wantX, wantY := tvx, tvy
	if dist >= settle {
		s := math.Min(maxSpeed, dist*arrive)
		wantX, wantY = tvx+dx/dist*s, tvy+dy/dist*s
	}
	dvx, dvy := wantX-p.vx, wantY-p.vy
	if dl, max := math.Hypot(dvx, dvy), accel*dt; dl > max {
		p.vx += dvx / dl * max
		p.vy += dvy / dl * max
	} else {
		p.vx, p.vy = wantX, wantY
	}
	p.X += p.vx * dt
	p.Y += p.vy * dt
	if math.Hypot(p.vx, p.vy) > 4 {
		p.H = math.Atan2(p.vy, p.vx)
	}
}

func (h *hub) step(dt float64) {
	h.time += dt
	for _, b := range h.bodies {
		b.place(h.time)
		if b.Kind != "barren" {
			continue
		}
		if b.wait -= dt; b.wait <= 0 {
			b.wait = oreWait()
			h.spawnOre(b)
		}
	}
	for _, o := range h.ore {
		h.stepOre(o, dt)
	}
	for _, p := range h.players() { // every hull, connected or not
		if p.AI {
			h.think(p, dt) // patrol a yard, or run down whoever it is fighting
		}
		var tvx, tvy float64
		if b := h.body(p.orbit); b != nil {
			// The ring point turns with the body around its star, so the ship is
			// carried with it even in another system. Keeping up with it is the
			// point's own velocity, which grows with the ring: chasing only where it
			// was leaves the ship parked short of a fast body and never docked.
			d := b.speed * (h.time - p.anchored)
			cs, sn := math.Cos(d), math.Sin(d)
			p.TX = b.cx + p.ox*cs - p.oy*sn
			p.TY = b.cy + p.ox*sn + p.oy*cs
			tvx, tvy = b.speed*-(p.TY-b.cy), b.speed*(p.TX-b.cx)
		}
		if o := h.player(p.chase); o != nil {
			tvx, tvy = 0, 0 // the hull being closed on is aimed at, not led
			if math.Hypot(o.X-p.X, o.Y-p.Y) > gunRange*approach {
				p.TX, p.TY = o.X, o.Y // close in until the guns can reach
			} else {
				p.TX, p.TY = p.X, p.Y // in range: settle and keep shooting
			}
		}
		p.steer(dt, tvx, tvy)
		// An order is spent once the ship reaches it, and a spent order is nothing to
		// mark: a point when the ship settles on it, an orbit when it is docked on the
		// ring. A flown point stops being a target at all; an orbit has to keep its
		// turning ring point, or the ship would be left standing still.
		r := settle
		if p.orbit != 0 {
			r = dockR
		}
		p.Order = math.Hypot(p.TX-p.X, p.TY-p.Y) >= r
		if !p.Order && p.orbit == 0 {
			p.TX, p.TY = p.X, p.Y
		}
		h.burn(p, dt)
		h.haul(p)
		h.guns(p, dt)
		p.FuelMax = p.capacity()
		h.drive(p, dt)
		if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" && p.docked() {
			h.yard(p, dt)
		}
		for i, id := range p.tow {
			if o := h.oreByID(id); o != nil {
				h.onLine(o, p, float64(i+1))
			}
		}
		if p.Pieces[0].HP == 0 || p.Fuel == 0 {
			h.die(p) // the root piece is the run itself, and so is the tank
		}
	}
	h.stepShots(dt)
	h.stepAI(dt)
	h.stepLoose(dt)
}

// A root piece at zero, or a dry tank, ends that hull. A player is replaced at
// once under a new id, so the client snaps there; an AI leaves a wreck and comes
// back to its own shipyard after a delay.
func (h *hub) die(p *player) {
	if p.AI {
		h.bury(p)
		return
	}
	for c := range h.clients {
		if c.p == p {
			c.p = h.respawn(p)
			return
		}
	}
}

func (h *hub) tick() {
	for range time.Tick(time.Second / tickRate) {
		h.mu.Lock()
		h.step(tickDt)
		players := h.players()
		// Marshal under the lock: the state is shared, not copied per client.
		out := make(map[*client][]byte, len(h.clients))
		for c := range h.clients {
			b, err := json.Marshal(state{
				T: "state", You: c.p.ID, Held: c.p.held,
				Bodies: h.bodies, Systems: h.systems, Loose: h.loose, Ore: h.ore, Shots: h.shots, Players: players,
			})
			if err == nil {
				out[c] = b
			}
		}
		h.mu.Unlock()

		for c, b := range out {
			c.ws.SetWriteDeadline(time.Now().Add(2 * time.Second))
			c.ws.WriteMessage(websocket.TextMessage, b)
		}
	}
}
