local class = require("core.class")
local Sequence = class.Class("Sequence")
function Sequence:init(ai)
  self.list = {}
  self.ai = ai
end
function Sequence:At(time, callback, ...)
  self.list[#self.list + 1] = {
    time_absolute = time,
    callback = callback,
    args = (...) and {
      ...
    },
    debug = function()
      return string.format("t >= %.2f", time)
    end
  }
end
function Sequence:When(cond, callback, ...)
  self.list[#self.list + 1] = {
    condition = cond,
    callback = callback,
    args = (...) and {
      ...
    },
    debug = function()
      return "When"
    end
  }
end
function Sequence:Always(callback, ...)
  self.list[#self.list + 1] = {
    callback = callback,
    args = (...) and {
      ...
    },
    debug = function()
      return "Always"
    end
  }
end
function Sequence:WaitForMoveEnd(move_name)
  self.list[#self.list + 1] = {
    condition = function()
      return move_name and self.ai:IsPlayingMove(move_name) or self.ai:IsInNavigationMove()
    end,
    debug = function()
      return string.format("MoveEnd(%s)", move_name or "<current>")
    end
  }
end
function Sequence:WaitForMoveStart(move_name)
  assert(move_name)
  self.list[#self.list + 1] = {
    condition = function()
      local playing = self.ai:IsPlayingMove(move_name)
      local cancel = not playing and self.ai:IsInNavigationMove()
      return playing, cancel
    end,
    debug = function()
      return string.format("MoveStart(%s)", move_name or "<current>")
    end
  }
end
function Sequence:AtMoveEnd(move_name, ...)
  local move_name_given = type(move_name) ~= "function"
  if move_name_given then
    self:WaitForMoveEnd(move_name)
    self:Always(...)
  else
    self:WaitForMoveEnd()
    self:Always(move_name, ...)
  end
end
function Sequence:AtMoveStart(move_name, ...)
  self:WaitForMoveStart(move_name)
  self:Always(...)
end
function Sequence:AtMovePercent(move_name, pct, ...)
  if type(move_name) == "number" then
    self:AtSpecificMovePercent(nil, move_name, pct, ...)
  else
    self:AtSpecificMovePercent(move_name, pct, ...)
  end
end
function Sequence:AtSpecificMovePercent(move_name, pct, callback, ...)
  self.list[#self.list + 1] = {
    condition = function()
      local cancel = move_name and self.ai:IsInNavigationMove()
      local check = not move_name or self.ai:IsPlayingMove(move_name)
      return check and self.ai:GetActiveMovePercent() >= pct, cancel
    end,
    debug = function()
      return string.format("MovePercent(%s) >= %.2f", move_name or "<current>", pct)
    end,
    callback = callback,
    args = (...) and {
      ...
    }
  }
end
return {Sequence = Sequence}
