local class = require("core.class")
local levelmonitor = require("level.levelmonitor")
local DeathMonitor = class.Class("DeathMonitor", levelmonitor.LevelMonitor)
local callDeathCallback
function DeathMonitor:OnDeath(fn, ...)
  self.deathCallbacks[#self.deathCallbacks + 1] = {
    fn = fn,
    ...
  }
  self:OnChanged(callDeathCallback, self)
end
local AddDeathMonitor = function(ai)
  return DeathMonitor.New(ai)
end
function callDeathCallback(oldValue, newValue, self)
  local foundValidCallback = false
  if newValue == true and oldValue == false then
    for _, f in pairs(self.deathCallbacks) do
      self:dprint("Health Monitor triggered, enemy is dead - " .. tostring(self.ai))
      f.fn(self, unpack(f))
      foundValidCallback = foundValidCallback or true
    end
    self:Stop()
  end
  return foundValidCallback
end
function DeathMonitor:init(ai)
  self.ai = ai
  if self.ai ~= nil then
    self.value = self.ai:IsDead()
  else
    self.value = false
  end
  self:Watch(self.watch_callback, self)
  self.deathCallbacks = {}
  self:Start()
end
function DeathMonitor:watch_callback()
  if self.ai == nil then
    return self.value
  else
    return self.ai:IsDead()
  end
end
_G.AddDeathMonitor = AddDeathMonitor
return {DeathMonitor = DeathMonitor, Add = AddDeathMonitor}
