local DL = require("design.DesignerLibrary")
local bboardUtil = require("game.BlackboardUtil")
local lineTrail, orbObject, trackObject
local shockExploded = false
local concussionType = "CNC_LIGHTNING_AXE_COMBO"
local delayedInit = 0
local lifeTime = 8
function OnScriptLoaded(level, go, ...)
end
function OnUpdate(level, go)
  if delayedInit == 1 then
    trackObject = go
    delayedInit = delayedInit + 1
  else
    delayedInit = delayedInit + 1
    if delayedInit == 1 then
      return
    end
  end
  if trackObject == nil then
    shockExploded = true
  end
  if shockExploded == false then
    if lifeTime <= 0 then
      local concussionParams = {}
      concussionParams.WorldLocation = trackObject.WorldPosition
      concussionParams.Creature = game.AI.FindSon()
      concussionParams.EnemyId = DL.HashCreatureID(game.Player.FindPlayer(), "SON00")
      concussionParams.Tweak = "CNC_LIGHTNING_AXE_COMBO"
      game.Combat.PlayConcussion(concussionParams)
      shockExploded = true
    else
      MoveLineTrail(level, go, trackObject.WorldPosition)
      EmitArrows(level, trackObject.WorldPosition)
      lifeTime = lifeTime - level:GetUnitTime()
    end
  else
    if lineTrail ~= nil then
      lineTrail:Destroy()
    end
    if orbObject ~= nil then
      orbObject:Destroy()
    end
    go:Destroy()
  end
end
local tickTimer = 0.1
local currentTickTimer = 0
local shotRadius = 10
local shockCount = 1
function EmitArrows(level, newPos)
  if currentTickTimer >= tickTimer then
    currentTickTimer = 0
    tickTimer = math.random() * 0.25
    local player = game.Player.FindPlayer()
    local enemies = player:FindEnemies(100)
    local enemiesInRange = {}
    for _, i in ipairs(enemies) do
      if (i.WorldPosition - newPos):Length() < shotRadius then
        table.insert(enemiesInRange, i)
      end
    end
    for _ = 1, shockCount do
      if 0 < #enemiesInRange then
        local randomIndex = math.random(1, #enemiesInRange)
        local son = game.AI.FindSon()
        local arrowData = {}
        arrowData.Tweak = "ARR_ARROW_SHOCK_ARC_MINI_LUA"
        arrowData.Creator = son
        local angle = DL.GetAngleFromVectors(son:GetWorldForward(), engine.Vector.New(1, 0, 0))
        arrowData.EmitOffset = (newPos - son.WorldPosition - engine.Vector.New(0, 0, -1)):RotateXZ(angle - 90) + engine.Vector.New(0, newPos.y, 0)
        arrowData.Target = enemiesInRange[randomIndex]
        game.Combat.EmitArrow(arrowData)
      end
    end
  end
  currentTickTimer = currentTickTimer + level:GetUnitTime()
end
function MoveLineTrail(level, go, newPos)
  if lineTrail == nil then
    lineTrail = game.FX.Spawn("Electric_Ground_Shock", level)
  end
  if orbObject == nil then
    orbObject = game.FX.Spawn("ArcShot_Light_Shot_Orb", level)
  end
  orbObject:SetWorldPosition(newPos)
  lineTrail:SetWorldPosition(newPos)
end
