// The server owns everything a client draws: celestial bodies, ships, hulls and
// loose pieces. Clients send intents (pick, drag, drop) and render the state
// they are handed.

package main

import (
	"encoding/json"
	"flag"
	"log"
	"math"
	"net/http"
	"strconv"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}

var addr = flag.String("addr", ":8090", "listen address")

func main() {
	flag.Parse()
	h := newHub()
	go h.tick()
	http.HandleFunc("/ws", h.handle)
	http.HandleFunc("/debug/state", h.debugState)
	log.Fatal(http.ListenAndServe(*addr, nil))
}

func newHub() *hub {
	h := &hub{clients: map[*client]bool{}, loose: []*loose{}, ore: []*ore{}}
	// Empty, not nil: a nil slice marshals as null, and the client walks these.
	h.galaxy() // ten star systems, drawn fresh on every boot: there is no seed
	// Place the bodies before anything is born around them, then fill every yard
	// with its passive AI traffic. A run starts at any yard near the middle, so new
	// ships spread over the inner systems instead of stacking on one ring.
	for _, b := range h.bodies {
		b.place(0)
		if b.Kind != "shipyard" {
			continue
		}
		if math.Hypot(b.cx, b.cy) < rimRing {
			h.spawns = append(h.spawns, b.ID)
		}
		for i := 0; i < aiPerYard; i++ {
			h.ai = append(h.ai, h.spawnAI(b))
		}
	}
	h.rogues() // the gaps between the stars, after the systems are where they are
	log.Printf("galaxy: %d systems, %d bodies", 1+midCount+rimCount, len(h.bodies))
	return h
}

func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	h.mu.Lock()
	h.nextID++
	c := &client{ws: ws, p: &player{ID: h.nextID}}
	c.p.Name = "P" + strconv.Itoa(c.p.ID)
	c.p.Pieces = []piece{h.fitted("triangle", 0)} // every run starts from one triangle
	c.p.FuelMax = c.p.capacity()
	c.p.Fuel = c.p.FuelMax
	h.deploy(c.p)
	h.clients[c] = true
	h.mu.Unlock()

	for {
		_, msg, err := ws.ReadMessage()
		if err != nil {
			break
		}
		var in struct {
			T string   `json:"t"`
			X *float64 `json:"x"`
			Y *float64 `json:"y"`
		}
		if json.Unmarshal(msg, &in) != nil {
			continue
		}
		if in.X == nil || in.Y == nil || !finite(*in.X) || !finite(*in.Y) {
			continue
		}
		if math.Abs(*in.X) > reach || math.Abs(*in.Y) > reach {
			continue
		}
		h.mu.Lock()
		switch in.T {
		case "pick":
			h.pick(c.p, *in.X, *in.Y)
		case "drag":
			h.drag(c.p, *in.X, *in.Y)
		case "drop":
			h.drop(c.p, *in.X, *in.Y)
		}
		h.mu.Unlock()
	}

	h.mu.Lock()
	delete(h.clients, c)
	h.forgive(c.p.ID)
	h.abandon(c.p)
	h.mu.Unlock()
	ws.Close()
}

// The same state the websocket pushes, for a test that only needs to look: no
// client, so you and held are zero. The socket stays the only way to act.
func (h *hub) debugState(w http.ResponseWriter, r *http.Request) {
	h.mu.Lock()
	b, err := json.Marshal(state{T: "state", Bodies: h.bodies, Systems: h.systems, Loose: h.loose, Ore: h.ore, Shots: h.shots, Players: h.players()})
	h.mu.Unlock()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(b)
}
