package main

import (
	"math"
	"sync"

	"github.com/gorilla/websocket"
)

const (
	tickRate = 20
	tickDt   = 1.0 / tickRate

	standoff = 26.0 // ring radius beyond a planet's surface
	starGap  = 34.0 // a star kills on contact, so its ring sits further out
	hitR     = 1.5  // click radius of a body, as a multiple of its radius
	spacing  = 17.0 // world distance between attached piece centers
	slots    = 6    // attachment directions around a hull piece
	// A piece you have just torn off sits one spacing out of the hull, and the outer
	// pieces of a big hull sit two, so the hand has to reach that far to reach them.
	handR    = 2 * spacing
	maxSpeed = 90.0
	accel    = 260.0
	arrive   = 2.2    // slowdown radius factor
	settle   = 0.5    // a ship this close to its target has arrived and stops thrusting
	reach    = 4000.0 // an order further out than this is ignored

	oreGap     = 15.0 // closest two ore may sit: also the spacing of the rings
	oreRings   = 4    // rings a barren planet can park ore on
	oreRingMin = 12.0 // first ring's distance beyond the surface
	oreBrake   = 10.0 // outward deceleration, so a launch coasts out then parks
	oreOrbitV  = 12.0 // world units per second travelled along a ring
	oreTouch   = 14.0 // flying this close to ore hooks it onto the line
	towGap     = 12.0 // distance between ore on a tow line
	oreWaitMin = 30.0 // a barren planet throws an ore every 30-60s
	oreWaitMax = 60.0
	oreHolds   = 3 // a barren planet holds 3-6 ore, a fixed count per planet

	pieceR  = 11.0 // world radius of a piece: its outline, and its share of a star
	burn    = 5.0  // hit points a second a piece loses inside a star
	dockR   = 8.0  // the ship counts as docked inside this of its ring point
	towBase = 3    // ore a hull can haul with no circle at all
	towPer  = 3    // extra ore each circle adds to the line
	maxTier = 2    // a piece can be upgraded twice
	yardOre = 3    // ore a shipyard takes for one service
	yardGap = 1.0  // seconds between services, so a full line drains visibly

	fuelPer = 1800.0 // world units of travel one unit of fuel buys
	refuel  = 1.0    // fuel a second a docked shipyard puts back in the tank

	aiPerYard  = 2    // police ships a shipyard keeps in orbit
	aiDelay    = 25.0 // seconds after a police death before that yard births another
	aiMin      = 1    // ship pieces the smallest police hull is born with
	aiMax      = 2    // and the largest a yard fields
	patrolSpin = 0.18 // radians a second an AI circles its yard on patrol
	patrolLow  = 6.0  // the tightest patrol line sits this far beyond the standoff
	patrolHigh = 30.0 // and the widest this much further out again

	// The two factions a server hull can belong to. A connected player has no side:
	// players are only at war with whoever declared it.
	sidePolice = "police"
	sideRogue  = "rogue"

	rogueMidN      = 2 // rogue patrols in the gaps of the middle galaxy ring
	rogueRimN      = 6 // and in the gaps of the rim, so danger grows outward
	rogueMidPieces = 2 // piece count of a middle-ring rogue hull, plus
	rogueMidVar    = 2 // this much more drawn per hull
	rogueRimPieces = 3 // a rim rogue is bigger still
	rogueRimVar    = 3
	rogueMidTier   = 1     // best tier a middle-ring hull is built from
	rogueRimTier   = 2     // and the rim's, so going out buys quality and not only bulk
	rogueDelay     = 25.0  // seconds a dead rogue's point stays quiet
	rogueLeash     = 300.0 // how far from that point it runs a target down
	rogueClear     = 500.0 // a rogue point keeps this far from every star system
	rogueRingLow   = 80.0  // patrol circle around that point, plus
	rogueRingVar   = 120.0 // this much more per hull
	wreckTTL       = 60.0  // seconds a server hull's wreckage lies before it is gone

	gunRange  = 140.0 // world distance a triangle will shoot at
	gunCool   = 1.6   // seconds between salvos from one hull
	shotSpeed = 150.0 // a round is faster than a ship, so range alone is not safety
	shotDmg   = 3.0   // hit points one round takes off a piece
	approach  = 0.8   // of gun range: an approach order closes to here, no further
)

// A hull is a graph of pieces placed relative to the ship. Piece ids are unique
// across the whole world, so a piece can be torn off one hull and bolted to
// another without ever changing identity.
type piece struct {
	ID     int     `json:"id"`
	Kind   string  `json:"kind"`
	LX     float64 `json:"lx"`
	LY     float64 `json:"ly"`
	Parent int     `json:"parent"`
	HP     float64 `json:"hp"`
	MaxHP  float64 `json:"maxhp"`
	Tier   int     `json:"tier"`
}

type loose struct {
	ID    int     `json:"id"`
	Kind  string  `json:"kind"`
	X     float64 `json:"x"`
	Y     float64 `json:"y"`
	H     float64 `json:"h"`
	HP    float64 `json:"hp"`
	MaxHP float64 `json:"maxhp"`
	Tier  int     `json:"tier"`
	held  int     // player dragging it, 0 = free
	ttl   float64 // seconds until a server hull's wreckage is gone, 0 = it stays
}

// A shot is a real object in the world: it travels, it can be outrun sideways,
// and it only hurts the piece it actually crosses.
type shot struct {
	ID int     `json:"id"`
	X  float64 `json:"x"`
	Y  float64 `json:"y"`
	H  float64 `json:"h"`

	owner int     // player who fired it, immune to its own round
	left  float64 // world distance it can still travel
}

// An ore piece is thrown out of a barren planet and parks in one of its rings.
// It lives in the planet's rotating frame (an angle and a radius), so it travels
// with the planet around the star, and it is only a world point once placed.
type ore struct {
	ID    int     `json:"id"`
	X     float64 `json:"x"`
	Y     float64 `json:"y"`
	H     float64 `json:"h"`
	Towed int     `json:"towed"` // player hauling it, 0 = loose

	planet int     // body it orbits, 0 = drifting where it was let go
	a      float64 // slot angle on its ring, in the planet's frame
	r      float64 // current distance from the planet centre
	vr     float64 // outward speed, 0 once it is parked in its ring
	ring   float64 // radius it settles into
}

// A body is a star or a planet. Orbit 0 and speed 0 is the star, which never
// moves; planets revolve around it, and their current place is recomputed every
// tick. cx, cy is the centre of the system the body belongs to, so a body is a
// world point without anything else having to know about systems.
type body struct {
	ID    int     `json:"id"`
	Kind  string  `json:"kind"`
	R     float64 `json:"r"`
	X     float64 `json:"x"`
	Y     float64 `json:"y"`
	cx    float64
	cy    float64
	orbit float64
	a0    float64
	speed float64
	wait  float64 // seconds until a barren planet throws its next ore
	cap   int     // how many ore this barren planet keeps in orbit
}

// A body's place is a pure function of world time: planets revolve around their
// star, and the star (orbit 0) sits still at its system's centre.
func (b *body) place(t float64) {
	a := b.a0 + b.speed*t
	b.X, b.Y = b.cx+math.Cos(a)*b.orbit, b.cy+math.Sin(a)*b.orbit
}

type player struct {
	ID      int     `json:"id"`
	Name    string  `json:"name"`
	Side    string  `json:"side"` // police or rogue for a server hull, empty for a player
	X       float64 `json:"x"`
	Y       float64 `json:"y"`
	H       float64 `json:"h"`
	TX      float64 `json:"tx"`
	TY      float64 `json:"ty"`
	Order   bool    `json:"order"` // the order is still pending, so it is still to be marked
	Pieces  []piece `json:"pieces"`
	Fuel    float64 `json:"fuel"`    // what is in the tank, spent by flying
	FuelMax float64 `json:"fuelmax"` // capacity, summed from the hull every tick
	Foe     int     `json:"foe"`     // ship this one is chasing, 0 = nobody
	Target  int     `json:"target"`  // piece of that ship the guns are pointed at
	AI      bool    `json:"ai"`      // a server-run hull, not a connection

	home     int     // shipyard body a police hull was born at, and comes back to
	spot     int     // rogue point a rogue patrols, as an index into hub.slots
	hx, hy   float64 // centre of a rogue's patrol circle, in world units
	angle    float64 // AI patrol angle around that yard or point
	ring     float64 // AI patrol radius around it
	spin     float64 // AI patrol angular speed, negative for the other way round
	chase    int     // ship this one was ordered to close on, 0 = no order
	cool     float64 // seconds until the guns can fire again
	vx, vy   float64
	orbit    int     // body the ship is anchored to, 0 = none
	ox, oy   float64 // ring point at anchoring, as an offset from the system centre
	anchored float64 // world time of anchoring
	held     int     // loose piece being dragged, 0 = none
	tow      []int   // ore on the tow line, in order behind the ship
	yard     float64 // seconds until a shipyard will take another load
}

type client struct {
	ws *websocket.Conn
	p  *player
}

// A wrecked AI is gone for a while, then its shipyard births a replacement.
type grave struct {
	home int
	wait float64
}

// A rogue point is a gap between two stars on a galaxy ring, and it holds exactly
// one rogue patrol: when that hull dies the point goes quiet, and births another
// after a delay. So a ring never runs out of patrols and never gains a second one.
type slot struct {
	x, y float64
	ring float64 // the galaxy ring the point sits on: it sets how big its hull is
	wait float64 // seconds until it births a hull, 0 while one is alive
}

type hub struct {
	mu        sync.Mutex
	clients   map[*client]bool
	nextID    int
	bodies    []*body
	systems   []*system
	spawns    []int // shipyard bodies a new run may be born in orbit of, never at the rim
	loose     []*loose
	ore       []*ore
	shots     []*shot
	ai        []*player // server-run hulls, tracked whether or not anyone is connected
	grave     []*grave
	slots     []*slot // the rogue points of the galaxy, one patrol each
	nextPiece int
	time      float64
}

type state struct {
	T       string    `json:"t"`
	You     int       `json:"you"`
	Held    int       `json:"held"`
	Bodies  []*body   `json:"bodies"`
	Systems []*system `json:"systems"`
	Loose   []*loose  `json:"loose"`
	Ore     []*ore    `json:"ore"`
	Shots   []*shot   `json:"shots"`
	Players []*player `json:"players"`
}

func (h *hub) pieceID() int {
	h.nextPiece++
	return h.nextPiece
}
