local class = require("core.class")
local levelmonitor = require("level.levelmonitor")
local AnimFrameMonitor = class.Class("AnimFrameMonitor", levelmonitor.LevelMonitor)
local callAnimFrameChangedCallback
function AnimFrameMonitor:OnFrame(frameNum, fn, ...)
  self.frameCallbacks[frameNum] = {
    fn = fn,
    ...
  }
  self:OnChanged(callAnimFrameChangedCallback, self)
end
function AnimFrameMonitor:OnFrameForward(frameNum, fn, ...)
  self.frameForwardCallbacks[frameNum] = {
    fn = fn,
    ...
  }
  self:OnChanged(callAnimFrameChangedCallback, self)
end
function AnimFrameMonitor:OnFrameBackward(frameNum, fn, ...)
  self.frameBackwardCallbacks[frameNum] = {
    fn = fn,
    ...
  }
  self:OnChanged(callAnimFrameChangedCallback, self)
end
local AddAnimFrameMonitor = function(go)
  return AnimFrameMonitor.New(go)
end
function callAnimFrameChangedCallback(oldValue, newValue, self)
  local foundValidCallback = false
  for v, f in pairs(self.frameCallbacks) do
    if oldValue < v and v <= newValue or v < oldValue and newValue <= v then
      self:dprint("Anim Frame Monitor triggered: Current frame on object '" .. tostring(self.go) .. "' crossed frame threshold (" .. tostring(v) .. ")")
      f.fn(self, unpack(f))
      foundValidCallback = foundValidCallback or true
    end
  end
  for v, f in pairs(self.frameForwardCallbacks) do
    if oldValue < v and v <= newValue then
      self:dprint("Anim Frame Monitor triggered: Current frame on object '" .. tostring(self.go) .. "' became greater than frame " .. tostring(v))
      f.fn(self, unpack(f))
      foundValidCallback = foundValidCallback or true
    end
  end
  for v, f in pairs(self.frameBackwardCallbacks) do
    if v < oldValue and newValue <= v then
      self:dprint("Anim Frame Monitor triggered: Current frame on object '" .. tostring(self.go) .. "' became less than frame " .. tostring(v))
      f.fn(self, unpack(f))
      foundValidCallback = foundValidCallback or true
    end
  end
  return foundValidCallback
end
function AnimFrameMonitor:init(go)
  self.go = go
  self.value = go.AnimFrame
  self:Watch(self.watch_callback, self)
  self.frameCallbacks = {}
  self.frameForwardCallbacks = {}
  self.frameBackwardCallbacks = {}
  self:Start()
end
function AnimFrameMonitor:watch_callback()
  if self.go.AnimFrame == nil then
    return self.value
  end
  return self.go.AnimFrame
end
_G.AddAnimFrameMonitor = AddAnimFrameMonitor
return {AnimFrameMonitor = AnimFrameMonitor, Add = AddAnimFrameMonitor}
