function epic.spray_foam(pos)
   for z = -4,4 do
      for y = -4,4 do
         for x = -4,4 do
            local p = {x=pos.x+x, y=pos.y+y, z=pos.z+z}
            local nn = minetest.get_node(p).name
            if nn == 'fire:basic_flame' then
               minetest.set_node(p, {name='air'})
               minetest.sound_play('fire_extinguish_flame',{pos = p, max_hear_distance = 16, gain = 0.15})
               minetest.check_for_falling(p)
            end
         end
      end
   end
end

local function throw_anti_fire_bomb(item, player)
   local playerpos = player:get_pos()
   local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.625,z=playerpos.z}, 'epic:anti_fire_entity')
   local dir = player:get_look_dir()
   obj:set_velocity({x=dir.x*30, y=dir.y*30, z=dir.z*30})
   obj:set_acceleration({x=dir.x*-3, y=-dir.y^8*80-10, z=dir.z*-3})
   item:take_item()
   return item
end

minetest.register_craftitem('epic:anti_fire_bomb', {
   description = 'Anti fire bomb',
   inventory_image = 'epic_anti_fire.png',
   on_use = throw_anti_fire_bomb
})

minetest.register_node('epic:fire_extinguishing_powder', {
   description = 'Anti fire powder',
   drawtype = 'signlike',
   tiles = {'epic_anti_fire_powder.png'},
   inventory_image = 'epic_anti_fire_powder.png',
   wield_image = 'epic_anti_fire_powder.png',
   paramtype = 'light',
   paramtype2 = 'wallmounted',
   sunlight_propagates = true,
   selection_box = {
		type = 'fixed',
		fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
	},
   collision_box = {
		type = 'fixed',
		fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
   },
   groups = {dig_immediate = 3, attached_node = 1, flammable = 1},
   on_burn = function(pos)
      epic.spray_foam(pos)
      minetest.remove_node(pos)
   end,
   on_ignite = function(pos)
      epic.spray_foam(pos)
      minetest.remove_node(pos)
   end,
})

minetest.register_craft({
   output = 'epic:anti_fire_bomb',
   recipe = {
      {'', 'epic:fire_extinguishing_powder', '',},
      {'epic:fire_extinguishing_powder', 'tnt:tnt_stick', 'epic:fire_extinguishing_powder',},
      {'', 'epic:fire_extinguishing_powder', '',}
   }
})

minetest.register_entity('epic:anti_fire_entity', {
   timer=0,
   collisionbox = {0,0,0,0,0,0},
   physical = false,
   textures = {'epic_anti_fire.png'},
   lastpos={},
   on_step = function(self, dtime)
      self.timer = self.timer + dtime
      local pos = self.object:get_pos()
      local node = minetest.get_node(pos)
      if self.lastpos.x~=nil then
         if node.name ~= 'air' then
            self.object:remove()
            epic.spray_foam(self.lastpos)
            minetest.sound_play('tnt_explode', {pos = pos, max_hear_distance = 24, gain = 0.5})
         end
      end
      self.lastpos={x=pos.x, y=pos.y, z=pos.z}
   end
})
