local LD = require("design.LevelDesignLibrary")
local thisObj, luaCallbacks, breakEventAttr, parentBreakable
local enabled = true
function OnScriptLoaded(level, obj)
  thisObj = obj
  parentBreakable = thisObj.Parent
  if not thisObj.IsRefNode then
    parentBreakable = parentBreakable.Parent
  end
  if parentBreakable then
    parentBreakable = parentBreakable:GetBreakable()
  end
  breakEventAttr = obj:FindLuaTableAttribute("Event_OnBroken")
  game.SubObject.Sleep(obj)
  SoundInit()
  AddAxeTarget()
end
function OnSaveCheckpoint(level, obj)
  return {enabled = enabled}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  enabled = savedInfo.enabled
end
function OnBroken(fn)
  if luaCallbacks == nil then
    luaCallbacks = {}
  end
  luaCallbacks[#luaCallbacks + 1] = fn
end
function ExecuteLuaCallbacks()
  if luaCallbacks ~= nil and enabled then
    for _, callback in pairs(luaCallbacks) do
      callback()
    end
  end
end
function OnBreakableBroken(level, obj)
  if breakEventAttr ~= nil and enabled then
    LD.ExtractAndExecuteCallbacksForEvent(level, obj, breakEventAttr, "Breakable is now Broken")
  end
  ExecuteLuaCallbacks()
  ForceBreakParent()
  thisObj:RemoveThrowableTarget({JointName = "AxeJoint"})
  PlaySoundOnBreak()
end
function IsEnabled()
  return enabled
end
function Disable()
  enabled = false
end
function HideBreakableBehavior()
  thisObj:HideBehaviors()
  thisObj:HideCollision()
end
function ShowBreakableBehavior()
  thisObj:ShowBehaviors()
  thisObj:ShowCollision()
end
function ForceBreakParent()
  if parentBreakable then
    parentBreakable:Break()
  end
end
function AddAxeTarget()
  thisObj:AddThrowableTarget({
    JointName = "AxeJoint",
    AttachName = "ATT_Axe",
    OutwardRadius = 0.7,
    ReturnRadius = 0,
    ClampRadius = 0.4
  })
end
local soundEmitter
local soundEvents = {
  OnBreak = "SND_BRK_Metal_Hook_01"
}
function SoundInit()
  soundEmitter = thisObj:FindSingleSoundEmitterByName("SNDSHook")
end
function SoundSetup(sounds)
  if sounds ~= nil then
    if sounds.SoundEmitter ~= nil then
      soundEmitter = thisObj:FindSingleSoundEmitterByName(sounds.SoundEmitter)
    end
    for key in pairs(soundEvents) do
      for newKey, newValue in pairs(sounds) do
        if newKey == key and newValue ~= nil and newValue ~= "" then
          soundEvents[key] = newValue
        end
      end
      LD.SoundDebug(tostring(key) .. ": " .. tostring(soundEvents[key]))
    end
  end
end
function PlaySoundOnBreak()
  LD.PlaySound(soundEmitter, soundEvents.OnBreak)
end
