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

local this=nil
local ps=nil
local dir_vectors = { { 1,0 }, { 0,1 }, { -1,0 }, { 0,-1} }

function choose_direction()
   local tile_pos=get_tile_pos(this)
   local count=0
   while (count<5) do
      local dir=random(0,3)
      local v=dir_vectors[dir+1]
      -- Check if the imp can walk that way
      local new_pos=add_vec2(tile_pos,v)
      local b=can_walk(new_pos)
      if (b) then
         return v
      end
      count=count+1
   end
   return { 0,0 }
end

function init(t)
   this=t

   ps=instance_particle_system("fire_foot",{0,0,0})
   link_object(ps,this)

   -- Do AI
   while (true) do
      coroutine.yield()
      -- Choose random direction
      local dir=choose_direction()
      set_movement_vector(this,{ 0.0025*dir[1], 0, -0.0025*dir[2] })

      local v=get_movement_vector(this)
      while ((v[1]~=0) or (v[3]~=0)) do
         coroutine.yield()
         v=get_movement_vector(this)

         -- Check if the player has come within the radius
         local player=get_player()
         if (get_frame(player)~=frame_death) then
            local player_pos=get_object_world_pos(player)
            local obj_pos=get_object_world_pos(this)
            local delta=vec3_sqr_dist(player_pos,obj_pos)
            while (delta<36) do
               -- Enter pursuit mode
               set_movement_vector(this,sub_vec3(player_pos,obj_pos))
               coroutine.yield()
               player=get_player()
               player_pos=get_object_world_pos(player)
               obj_pos=get_object_world_pos(this)
               delta=vec3_sqr_dist(player_pos,obj_pos)
               if (get_frame(player)==frame_death) then delta=1000 end
            end
         end
      end
   end
end

function on_death()
   play_sound("die_imp",1)
   set_movement_vector(this,{0,0,0})
   local p=get_object_world_pos(this)
   instance_particle_system("puff_fire",p)
   wait_time(600)
   set_particle_system_life(ps,0)
   unlink_object(ps)
   kill_game_sprite(this)
end

function trigger_unsummon()
   start_sprite_thread(this,"on_death")
end
