local function throw_snowball(item, player)
   local playerpos = player:get_pos()
   local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.625,z=playerpos.z}, 'epic:snowball')
   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_entity('epic:snowball', {
   timer=0,
   collisionbox = {0,0,0,0,0,0},
   physical = false,
   textures = {'default_snowball.png'},
   lastpos={},
   on_step = function(self, dtime)
      self.timer = self.timer + dtime
      local pos = self.object:get_pos()
      local node = minetest.get_node(pos)
      local objs = minetest.env:get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 1)
      for k, obj in pairs(objs) do
         if obj:get_luaentity() ~= nil then
            if obj:get_luaentity().name ~= "epic:snowball" and obj:get_luaentity().name ~= "__builtin:item" then
               local damage = 1
               obj:punch(self.object, 1.0, {
                  full_punch_interval=1.0,
                  damage_groups={fleshy=damage},
               }, nil)
               self.object:remove()
            end
         else
            local damage = 1
            obj:punch(self.object, 1.0, {
               full_punch_interval=1.0,
               damage_groups={fleshy=damage},
            }, nil)
            self.object:remove()
         end
      end
      if self.lastpos.x~=nil then
         if node.name ~= 'air' then
            self.object:remove()
            minetest.set_node(self.lastpos, {name='epic:snow'})
            minetest.check_for_falling(self.lastpos)
         end
      end
      self.lastpos={x=pos.x, y=pos.y, z=pos.z}
   end
})

minetest.override_item('default:snow', {
   on_use = throw_snowball
})

minetest.override_item('trail:snow', {
   on_use = throw_snowball
})

minetest.register_node("epic:snow", {
	description = "Snow",
	tiles = {"default_snow.png"},
	inventory_image = "default_snowball.png",
	wield_image = "default_snowball.png",
	paramtype = "light",
	buildable_to = true,
	floodable = true,
	drawtype = "nodebox",
	node_box = {
		type = "fixed",
		fixed = {
			{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5},
		},
	},
	collision_box = {
		type = "fixed",
		fixed = {
			{-0.5, -0.5, -0.5, 0.5, -6 / 16, 0.5},
		},
	},
	groups = {crumbly = 3, falling_node = 1, snowy = 1, not_in_creative_inventory=1},
	sounds = default.node_sound_snow_defaults(),

	on_construct = function(pos)
		pos.y = pos.y - 1
		if minetest.get_node(pos).name == "default:dirt_with_grass" then
			minetest.set_node(pos, {name = "default:dirt_with_snow"})
		end
	end,
   on_use = throw_snowball
})

minetest.register_abm({
   label = 'epic:snow melting',
   nodenames = {'epic:snow'},
   interval = 30,
   chance = 15,
   action = function(pos)
      minetest.set_node(pos, {name = 'air'})
   end
})
