local thunk = require("core.thunk")
local WEAK_MT = {__mode = "k"}
local g_vfsDebug, g_vfsDebug_YOffset, UNIT_Y, OFFSET
thunk.Install("OnScriptLoaded", function(lvl)
  g_vfsDebug = engine.VFSBool.New("Show Context Action Debug")
  g_vfsDebug_YOffset = engine.VFSInt.New("Context Action Debug Y Offset", 0, 80, 1)
  g_vfsDebug_YOffset.value = 2
  UNIT_Y = engine.Vector.New(0, 1, 0)
  OFFSET = UNIT_Y * 1
end)
local g_poiInstances = setmetatable({}, WEAK_MT)
local RED = 16711680
local BLUE = 255
local GREEN = 65280
local draw_debug = function(level)
  local r, g, b = 0, 128, 0
  local titleColor = engine.Vector.New(r, g, b)
  local debugTable = {
    Title = string.format("Context Action (POI) Instances (%s)", level.Name),
    TitleColor = titleColor,
    X = 2,
    Y = g_vfsDebug_YOffset.value,
    {
      "Refnode",
      "Priority",
      "State",
      "Timer",
      "Loop_action_timer"
    }
  }
  for wrapper in pairs(g_poiInstances) do
    local pos = wrapper.go:GetWorldPosition()
    local engaged = wrapper.engaged
    local puppeteer = wrapper.puppeteer
    local attributes = wrapper.attributes
    local enabled = puppeteer ~= nil
    local color = engaged and BLUE or enabled and GREEN or RED
    engine.DrawFillSphere(pos + OFFSET, 0.1, color)
    engine.DrawLine(pos, pos + OFFSET, color)
    if enabled and engaged then
      local puppet = puppeteer.Puppet
      if puppet then
        engine.DrawLine(puppet:GetWorldPosition() + OFFSET, pos + OFFSET, color)
      end
      if 0 < attributes.DisengageIfPlayerFurtherThan then
        engine.DrawSphere(pos, attributes.DisengageIfPlayerFurtherThan, color)
        engine.DrawCircle(pos + OFFSET, attributes.DisengageIfPlayerFurtherThan, UNIT_Y, color)
      end
    elseif 0 < attributes.AvailableRange then
      engine.DrawSphere(pos, attributes.AvailableRange, color)
      engine.DrawCircle(pos + OFFSET, attributes.AvailableRange, UNIT_Y, color)
    end
    local state = not enabled and "Disable" or wrapper.stageName or "Enabled"
    local timer
    if wrapper.cooldownTimeRemaining then
      state = "Cooldown"
      timer = wrapper.cooldownTimeRemaining
    elseif wrapper.engaged and wrapper.loopTimeRemaining then
      timer = wrapper.loopTimeRemaining
    end
    local loopActionTimer
    if wrapper.loopActionFreqTimeRemaining and 0 <= wrapper.loopActionFreqTimeRemaining then
      loopActionTimer = wrapper.loopActionFreqTimeRemaining
    end
    debugTable[#debugTable + 1] = {
      wrapper.go.Parent.Parent:GetDebugPath(),
      attributes.Priority,
      state,
      timer,
      loopActionTimer
    }
  end
  if 1 < #debugTable then
    engine.DrawDebugTable(debugTable)
  end
end
thunk.Install("OnUpdate", function(lvl)
  if g_vfsDebug.value == true and engine.IsDebug() then
    draw_debug(lvl)
  end
end)
local RegisterContextAction = function(wrapper)
  g_poiInstances[wrapper] = true
end
return {RegisterContextAction = RegisterContextAction}
