local class = require("core.class")
local statelogic = require("ai.statelogic")
local recursive_event_lookup = function(CLASS, event_table_name)
  return setmetatable({}, {
    __index = function(self, key)
      local PARENT = CLASS.PARENT
      while PARENT do
        local event = PARENT[event_table_name] and rawget(PARENT[event_table_name], key)
        if event then
          return event
        end
        PARENT = PARENT.PARENT
      end
    end
  })
end
local State = class.Class("State")
class.onSubclass(State, function(CLASS)
  CLASS.Name = CLASS.CLASSNAME
  CLASS.Events = recursive_event_lookup(CLASS, "Events")
  CLASS.Hooks = recursive_event_lookup(CLASS, "Hooks")
end)
function State:IsAvailable(...)
  local isActive = self:IsActive()
  assert(self.CanEnter, "Missing CanEnter function on %s", self.CLASSNAME)
  assert(self.ShouldExit, "Missing ShouldExit function on %s", self.CLASSNAME)
  if isActive then
    return not self:ShouldExit(...)
  else
    return self:CanEnter(...)
  end
end
function State:IsActive()
  local CI = statelogic.call_state()
  local activeState = CI.active_state
  local isActive = self == activeState
  return isActive
end
return {State = State}
