
std.include("scripts/common.lua")

local this=nil
local owner=nil
local pew={}
local charges=5
local directions={}
   directions[frame_north]={0,0,1}
   directions[frame_south]={0,0,-1}
   directions[frame_west]={-1,0,0}
   directions[frame_east]={1,0,0}

function init(t,o)
   this=t
   owner=o
end

function anim(t)
   for i,p in ipairs(pew) do
      local pos=get_object_world_pos(p.ps)
      pos=add_vec3(pos,{ p.dir[1]*t,p.dir[2]*t,p.dir[3]*t })
      set_object_world_pos(p.ps,pos)
      local t_pos=world_to_tile(pos)

      local sprites=get_sprites_in_radius(add_vec3(pos,{0,-1,0}),1)
      for j,s in ipairs(sprites) do
         if (get_sprite_name(s)=="imp") then
            send_event_to_sprite(s,"trigger_unsummon")
         end
      end

      if (not can_walk(t_pos)) then
         -- Hit wall - fizzle spell
         instance_particle_system("blue_dying_sparkles",pos)
         set_particle_system_life(p.ps,0)
         table.remove(pew,i)
      end
   end
end

function trigger()
   if (charges==0) then
      say(owner,"Oh no, no more charges!",1000,{ 0.2,1.0,0.1,1 })
      return
   end
   -- Instance particle system
   local pos=get_object_world_pos(owner)
   local psystem=instance_particle_system("yellow_sparkles",add_vec3(pos,{0,1,0}))
   local dir=get_sprite_direction(owner)

   local v=scale_vec3(directions[dir],0.02)

   table.insert(pew,{ ps=psystem, dir=v })

   charges=charges-1
end

function get_energy()
   return charges/5
end
