local async_util = require("async_util")

local paused = false

-- EMPs lock up the comms board. They won't clear
-- while we're paused, so we need to be careful.
local function isEMPActive()
  return (hv.Player:getEMP() or 0) > 0
end

local pause = (function()

  local sfx = ad.loadSoundfile("slowtime.ogg")

  return function()
    if paused or isEMPActive() then return end
    paused = true
    mn.runSEXP('( set-time-compression 0.1 1000 )')
    sfx:play(1.0, 0, false)
    async.run(function()
      async.await(async_util.wait_for(0.2))
      if hu.isCommMenuOpen() then
        ScpuiSystem:pauseAllAudio(true)
      end
    end, async.OnFrameExecutor)
  end

end)()

local resume = (function()

  local sfx = ad.loadSoundfile("restoretime.ogg")

  return function()
    if not paused then return end
    paused = false
    mn.runSEXP('( set-time-compression 100 1000 )')
    sfx:play(1.0, 0, false)
    async.run(function()
      async.await(async_util.wait_for(0.8))
      if not hu.isCommMenuOpen() then
        ScpuiSystem:pauseAllAudio(false)
        mn.runSEXP('( reset-time-compression )')
      end
    end, async.OnFrameExecutor)
  end

end)()

local function reset()
  paused = false
  mn.runSEXP('( reset-time-compression )')
end

-- Our "pause" is really just "extremely slow", so
-- it's possible for an EMP to start while paused.
local function check()
  if paused and isEMPActive() then resume() end
end

return {
  pause = pause,
  resume = resume,
  reset = reset,
  check = check
}

