local component = require("component")
local term = require("term")

if not term.isAvailable() then
  computer.beep()
  os.exit()
end

local function showError(message)
  component.gpu.setBackground(0x000000)
  component.gpu.setForeground(0xFF0000)
  local xt, yt = term.getCursor()
  component.gpu.set(xt, yt, message)
  component.gpu.setBackground(0x000000)
  component.gpu.setForeground(0xFFFFFF)
  print()
end

local function showErrorAndExit(message)
  showError(message)
  os.exit()
end

if not component.isAvailable("warpdriveRadar") then
  showErrorAndExit("No radar detected")
end

local radar = component.warpdriveRadar

local argv = { ... }
if #argv ~= 1 then
  showErrorAndExit("Usage: ping <scanRadius>")
end

local radius = tonumber(argv[1])

if radius < 1 or radius > 10000 then
  showErrorAndExit("Radius must be between 1 and 10000")
end
radar.radius(radius)

local success, result = radar.getEnergyRequired()
if not success then
  showErrorAndExit(result)
end
local energyRequired = result

local energyStored, _, energyUnits = radar.getEnergyStatus()
if energyStored < energyRequired then
  showErrorAndExit("Low energy level... (" .. energyStored .. "/" .. energyRequired .. " " .. energyUnits .. ")")
end

local scanDuration = radar.getScanDuration()
radar.start()
os.sleep(0.5)

print("Scanning... (" .. scanDuration .. " s)")
os.sleep(scanDuration)

local delay = 0
local count
repeat
  count = radar.getResultsCount()
  os.sleep(0.1)
  delay = delay + 1
until (count ~= nil and count ~= -1) or delay > 10

if count ~= nil and count > 0 then
  for i=0, count-1 do
    local success, type, name, x, y, z = radar.getResult(i)
    if success then
      print(type .. " " .. name .. " @ (" .. x .. " " .. y .. " " .. z .. ")")
    else
      showError("Error " .. type)
    end
  end
else
  print("Nothing was found =(")
end
