local tracker

-- The states a ship's thruster can be in. IN is used for a special case with arrival by subspace.
local THRUSTER_STATUS_OFF = 0
local THRUSTER_STATUS_ON  = 1
local THRUSTER_STATUS_IN  = 2

-- This class shouldn't ever have thruster glows.
local ATEN_HULK = tb.ShipClasses['PVC Aten#Hulk']

local function reset()
  tracker = {}
end

local function getStatus(ship, oldStatus)
  -- Special case 1: Disabled ships and hulks.
  if ship.Disabled or ship.Class == ATEN_HULK then
    return THRUSTER_STATUS_OFF
  end
  -- Special case 2: Arriving by subspace.
  -- isWarpingIn is true only briefly, before velocity is set.
  if ship:isWarpingIn() then
    return THRUSTER_STATUS_IN
  end
  local physics = ship.Physics
  -- If a ship is thrusting forward, turn its thrusters on.
  if physics.ForwardThrust > 0.01 then
    return THRUSTER_STATUS_ON
  -- Ditto ships that just emerged from a subspace aperture.
  elseif oldStatus == THRUSTER_STATUS_IN then
    return THRUSTER_STATUS_ON
  -- Revving up to depart doesn't immediately set the forward thrust.
  elseif ship:isDepartingWarp() then
    return THRUSTER_STATUS_ON
  -- If a ship has come to a complete stop, turn its thrusters off.
  elseif physics:getForwardSpeed() < 1 then
    return THRUSTER_STATUS_OFF
  -- If this is our first time seeing this ship, default to ON.
  elseif oldStatus == nil then
    return THRUSTER_STATUS_ON
  -- If none of the above hold, leave the thrusters alone.
  else
    return oldStatus 
  end
end

local function updateShip(ship)
  local signature = ship:getSignature()
  local oldStatus = tracker[signature]
  local newStatus = getStatus(ship, oldStatus)
  if oldStatus ~= newStatus then
    tracker[signature] = newStatus
    ship:setFlag(newStatus == THRUSTER_STATUS_OFF, 'no-thrusters')
  end
end

local function update()
  for ship in mn.getShipList() do
    updateShip(ship)
  end
end

return { update = update, reset = reset }

