package main

import (
	"math"
	"math/rand"
)

// A click is resolved by the server: grab a piece, tear one off, engage a ship,
// park on a body, or fly to a point. The client never decides which happened.
func (h *hub) pick(p *player, x, y float64) {
	// A piece is picked up by hand: the click lands on its outline, and the piece is
	// within arm's reach of the hull. Nothing else is grabbable, so a click on
	// wreckage across the system is only a move order.
	if l := h.looseAt(x, y); l != nil && math.Hypot(l.X-p.X, l.Y-p.Y) < handR {
		p.held, l.held = l.ID, p.ID
		return
	}
	if id := hullPieceAt(p, x, y); id != 0 {
		if off := h.detach(p, id); len(off) > 0 {
			h.loose = append(h.loose, off...)
			if l := h.looseByID(id); l != nil {
				p.held, l.held = id, p.ID
			}
			return
		}
	}
	for _, o := range h.players() {
		if o == p {
			continue
		}
		if id := hullPieceAt(o, x, y); id != 0 {
			h.engage(p, o, id)
			return
		}
	}
	if b := h.bodyAt(x, y); b != nil {
		h.anchor(p, b)
		return
	}
	p.chase = 0 // any other order takes the ship off its approach
	p.orbit = 0
	p.TX, p.TY = x, y
}

// Clicking a ship's piece is a declaration, not a shot: both hulls become hostile,
// the attacker closes to gun range, and its guns are pointed at the piece that was
// clicked. Nobody is hostile until someone says so. A third hull keeps whatever
// fight it was already in, so declaring on one enemy never calls off another.
func (h *hub) engage(p, o *player, piece int) {
	p.Foe, o.Foe, p.chase, p.orbit = o.ID, p.ID, o.ID, 0
	p.Target = piece
}

func (h *hub) drag(p *player, x, y float64) {
	l := h.looseByID(p.held)
	if l == nil || l.held != p.ID {
		return
	}
	l.X, l.Y = x, y
}

func (h *hub) drop(p *player, x, y float64) {
	l := h.looseByID(p.held)
	if l == nil {
		return
	}
	p.held, l.held = 0, 0
	l.X, l.Y = x, y
	h.attach(p, l)
}

// Flying over ore hooks it onto the line: no clicks and nothing to decide. The
// line only takes what the hull can haul, so a full ship flies past the rest.
func (h *hub) haul(p *player) {
	if p.AI {
		return // an AI carries nothing: ore only ever moves between players
	}
	for _, o := range h.ore {
		if len(p.tow) >= p.towLimit() {
			return
		}
		if o.Towed != 0 || math.Hypot(p.X-o.X, p.Y-o.Y) > oreTouch {
			continue
		}
		o.Towed, o.planet = p.ID, 0 // off the ring and onto the line
		p.tow = append(p.tow, o.ID)
	}
}

func (p *player) release(o *ore) {
	o.Towed = 0
	for i, id := range p.tow {
		if id == o.ID {
			p.tow = append(p.tow[:i], p.tow[i+1:]...)
			return
		}
	}
}

func (p *player) towLimit() int {
	n := towBase
	for _, q := range p.Pieces {
		if q.Kind == "circle" {
			n += towPer
		}
	}
	return n
}

// Docked means the ship has actually settled on its ring point, not that it is
// still crossing the system toward it: a yard only serves a ship that stopped.
func (p *player) docked() bool {
	return math.Hypot(p.X-p.TX, p.Y-p.TY) < dockR
}

// Fuel capacity is summed from the hull: every piece carries a little and the
// star carries most of it, so range is a decision about what you bolt on.
func (p *player) capacity() float64 {
	f := 0.0
	for _, q := range p.Pieces {
		_, u := stats(q.Kind, q.Tier)
		f += u
	}
	return f
}

// Fuel is spent by the distance flown, so a stopped ship spends nothing, and a
// ship settled in orbit is carried by the body for free. A docked shipyard fills
// the tank back up for free.
func (h *hub) drive(p *player, dt float64) {
	if p.AI {
		return // an AI never leaves its system, so range is not a thing it plays
	}
	if p.orbit != 0 && p.docked() {
		if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" {
			p.Fuel = math.Min(p.FuelMax, p.Fuel+refuel*dt)
		}
		return
	}
	p.Fuel = math.Max(0, p.Fuel-math.Hypot(p.vx, p.vy)*dt/fuelPer)
}

// A shipyard services one load of ore at a time: three ore patch the whole hull
// up, and once nothing is damaged the load buys a tier on a random piece that can
// still take one. A whole, fully upgraded ship has nothing to buy, so it keeps
// its ore and the yard does not fire.
func (h *hub) service(p *player) bool {
	hurt := false
	for i, q := range p.Pieces {
		if q.HP < q.MaxHP {
			hurt = true
			p.Pieces[i].HP = q.MaxHP
		}
	}
	if hurt {
		return true // repair first: a wreck is worth nothing upgraded
	}
	var open []int
	for i, q := range p.Pieces {
		if q.Tier < maxTier {
			open = append(open, i)
		}
	}
	if len(open) == 0 {
		return false
	}
	q := &p.Pieces[open[rand.Intn(len(open))]]
	q.Tier++
	q.MaxHP, _ = stats(q.Kind, q.Tier)
	q.HP = q.MaxHP // a yard upgrade comes out whole
	return true
}

// Ore handed over leaves the world with the line: the yard keeps it.
func (h *hub) spend(p *player) {
	for i := 0; i < yardOre && len(p.tow) > 0; i++ {
		o := h.oreByID(p.tow[0])
		if o == nil {
			p.tow = p.tow[1:] // an ore that is already gone can never stall the yard
			continue
		}
		p.release(o)
		h.removeOre(o.ID)
	}
}

// Whatever the ship was dragging stays where it was: a dead or departed hull takes
// nothing with it.
func (h *hub) abandon(p *player) {
	for _, id := range p.tow {
		if o := h.oreByID(id); o != nil {
			o.Towed = 0 // the line goes slack where the ship stopped
		}
	}
	if l := h.looseByID(p.held); l != nil {
		l.held = 0
	}
}

// A ship in orbit of a shipyard keeps handing over loads as long as it has
// enough ore on the line, one load a second so the yard can be watched working.
func (h *hub) yard(p *player, dt float64) {
	p.yard = math.Max(0, p.yard-dt)
	if p.yard > 0 || len(p.tow) < yardOre || !h.service(p) {
		return
	}
	h.spend(p)
	p.yard = yardGap
}
