core.register_entity("pyutest_fireworks:firework", {
	initial_properties = {
		visual = "upright_sprite",
		textures = { "pyutest-firework.png", "pyutest-firework.png" },
		physical = true,
		glow = core.LIGHT_MAX
	},

	on_activate = function(self)
		self.object:set_velocity(vector.new(0, 12, 0))
	end,

	on_step = function(self, dtime)
		local vel = self.object:get_velocity()
		if vel.y < 0 then
			self:explode()
			self.object:remove()
			return
		end

		vel.y = vel.y - 5 * dtime
		self.object:set_velocity(vel)
		self:trail()
	end,

	trail = function(self)
		local pos = self.object:get_pos() - vector.new(0, 1, 0)
		local velocity = vector.new(math.random(-1, 1), 0, math.random(-1, 1))

		if math.random(1, 2) == 1 then
			core.add_particle({
				pos = pos,
				size = 1.2,
				expirationtime = 0.6,
				glow = core.LIGHT_MAX,
				vertical = true,
				velocity = velocity,
				collisiondetection = true,
				collision_removal = true,
				texture = "pyutest-firework-trail1.png"
			})
		else
			core.add_particle({
				pos = pos,
				size = 1.2,
				expirationtime = 0.6,
				glow = core.LIGHT_MAX,
				vertical = true,
				velocity = velocity,
				collisiondetection = true,
				collision_removal = true,
				texture = "pyutest-firework-trail2.png"
			})
		end
	end,

	explode = function(self)
		local color = {
			r = math.random(50, 255),
			g = math.random(50, 255),
			b = math.random(50, 255),
		}
		local texture = string.format("pyutest-firework-blast.png^[colorize:%s", core.colorspec_to_colorstring(color))

		local pos = self.object:get_pos()

		for v in core.objects_inside_radius(pos, 3) do
			if v ~= self.object then
				PyuTest.deal_damage(v, 9, PyuTest.DAMAGE_TYPES.fireworks())
			end
		end

		core.add_particlespawner({
			amount = math.random(20, 40),
			time = 0.8,
			minexptime = 0.4,
			maxexptime = 1.4,
			minsize = 2,
			maxsize = 2,
			vertical = false,
			glow = core.LIGHT_MAX,

			collisiondetection = false,
			texture = texture,
			minpos = pos,
			maxpos = pos,
			minvel = vector.new(-6, -6, -6),
			maxvel = vector.new(6, 6, 6),
		})

		core.sound_play("pyutest_firework", {
			gain = 1.2,
			pos = pos,
		})
	end
})

PyuTest.make_item("pyutest_fireworks:firework", "Firework", {}, "pyutest-firework.png", {
	on_place = function(itemstack, placer, pointed_thing)
		if pointed_thing.type == "node" then
			local pos = pointed_thing.above
			core.add_entity(pos, "pyutest_fireworks:firework")
			itemstack:take_item()
		end

		return itemstack
	end,
	__on_dispense = function (pos, itemstack)
		core.add_entity(pos, "pyutest_fireworks:firework")
		itemstack:take_item()

		return itemstack
	end
})
