--
--   Interactive stargate control program
--   Shows stargate state and allows dialling
--   addresses selected from a list
--

dofile("config")

addresses = {
  {"Island", "FFOW-X48"},
  {"Mainland", "PFIV-8GF"},
  {"Nether", "ZFFB-XP8-1V"}
}

function showMenu()
  term.setCursorPos(1, 1)
  for i, na in pairs(addresses) do
    print(string.format("%d %s", i, na[1]))
  end
  print("")
  print("D Disconnect")
  print("O Open Iris")
  print("C Close Iris")
  print("Q Quit")
  print("")
  write("Option? ")
end

function getIrisState()
  ok, result = pcall(sg.irisState)
  return result
end

function showState()
  locAddr = sg.localAddress()
  remAddr = sg.remoteAddress()
  state, chevrons = sg.stargateState()
  energy = sg.energyAvailable()
  iris = getIrisState()
  showAt(30, 1, "Local:   " .. locAddr)
  showAt(30, 2, "Remote:  " .. (remAddr or ""))
  showAt(30, 3, "State:   " .. state)
  showAt(30, 4, "Energy:  " .. energy)
  showAt(30, 5, "Iris:    " .. iris)
  showAt(30, 6, "Engaged: " .. chevrons)
end

function showAt(x, y, s)
  term.setCursorPos(x, y)
  write(string.rep(" ", 20))
  term.setCursorPos(x, y)
  write(s)
end

function showMessage(mess)
  term.setCursorPos(1, 19)
  term.clearLine()
  if mess then
    write(mess)
  end
end

function showError(mess)
  i = string.find(mess, ": ")
  if i then
    mess = "Error: " .. string.sub(mess, i + 2)
  end
  showMessage(mess)
end

handlers = {}

function dial(name, addr)
  showMessage(string.format("Dialling %s (%s)", name, addr))
  sg.dial(addr)
end

function handlers.char(c)
  if c == "d" then
    sg.disconnect()
  elseif c == "o" then
    sg.openIris()
  elseif c == "c" then
    sg.closeIris()
  elseif c == "q" then
    running = false
  elseif c >= "1" and c <= "9" then
    na = addresses[tonumber(c)]
    if na then
      dial(na[1], na[2])
    end
  end
end

function handlers.sgChevronEngaged(args)
  showMessage(string.format("Chevron %s engaged! (%s)", args.chevron(), args.symbol()))
end

function eventLoop()
  while running do
    showState()
    event, arg = os.pullEvent()
    f = handlers[event]
    if f then
      showMessage("")
      ok, result = pcall(f, arg)
      if not ok then
        showError(result)
      end
    end
  end
end

function main()
  term.clear()
  showMenu()
  eventLoop()
  term.clear()
  term.setCursorPos(1, 1)
end

running = true
main()
