local LD = require("design.LevelDesignLibrary")
local STATE_INIT, STATE_PRIMED, STATE_EXPLODE, STATE_DESTROYED = 0, 1, 2, 3
local thisEmitter
local state = STATE_INIT
local objectPosition, creatureOwner, fxRay, fxSparks, explosionTime, soundStart, soundLoop
function OnScriptLoaded(level, obj)
  thisEmitter = obj:FindSingleSoundEmitterByName("SNDObject")
  objectPosition = obj:GetWorldPosition()
  creatureOwner = obj:GetEffectObjectCreator()
  explosionTime = 4
  soundStart = obj:FindLuaTableAttribute("soundStart")
  soundLoop = obj:FindLuaTableAttribute("soundLoop")
  LD.PlaySound(thisEmitter, soundStart)
end
function OnStart(level, obj)
  _G.StartLevelTimer(explosionTime - 0.45, function()
    EmitLightning(level, obj)
  end)
  _G.StartLevelTimer(explosionTime, function()
    TriggerExplosion(level, obj)
  end)
  LD.PlaySound(thisEmitter, "SND_CHR_Dragon_XPL_Mortar_Projectile_Incoming")
end
function OnUpdate(level, obj)
  if state == STATE_INIT then
    state = STATE_PRIMED
    LD.PlaySound(thisEmitter, soundLoop)
  elseif state == STATE_EXPLODE then
    obj:Destroy()
    state = STATE_DESTROYED
  end
end
function TriggerExplosion(level, obj)
  LD.StopSound(thisEmitter, soundLoop)
  state = STATE_EXPLODE
end
function EmitLightning(level, obj)
  local arrowData = {}
  LD.PlaySound(thisEmitter, "SND_CHR_Dragon_XPL_Mortar_Projectile_Explo")
  arrowData.Tweak = "ARR_DRAGON_MORTAR_LIGHTNING_STRIKE_LUA"
  arrowData.Creator = creatureOwner
  arrowData.Level = level
  arrowData.EmitLocation = objectPosition + obj:GetWorldUp() * 45
  arrowData.TargetLocation = objectPosition
  game.Combat.EmitArrow(arrowData)
  local concussionParams = {
    Tweak = "CNC_DRAAGON_MORTAR_EXPLODE",
    WorldLocation = objectPosition,
    Creature = creatureOwner,
    EnemyId = creatureOwner:GetID()
  }
  game.Combat.PlayConcussion(concussionParams)
end
