-- Thanks Minecraft wiki! https://minecraft.wiki/w/Note_Block
local NOTES = {
	{2^(-12/12), "#77D700"},
	{2^(-11/12), "#95C000"},
	{2^(-10/12), "#B2A500"},
	{2^(-9/12), "#CC8600"},
	{2^(-8/12), "#E26500"},
	{2^(-7/12), "#F34100"},
	{2^(-6/12), "#FC1E00"},
	{2^(-5/12), "#FE000F"},
	{2^(-4/12), "#F70033"},
	{2^(-3/12), "#E8005A"},
	{2^(-2/12), "#CF0083"},
	{2^(-1/12), "#AE00A9"},
	{2^(0/12), "#8600CC"},
	{2^(1/12), "#5B00E7"},
	{2^(2/12), "#2D00F9"},
	{2^(3/12), "#020AFE"},
	{2^(4/12), "#0037F6"},
	{2^(5/12), "#0068E0"},
	{2^(6/12), "#009ABC"},
	{2^(7/12), "#00C68D"},
	{2^(8/12), "#00E958"},
	{2^(9/12), "#00FC21"},
	{2^(10/12), "#1FFC00"},
	{2^(11/12), "#59E800"},
	{2^(12/12), "#94C100"},
}

local NOTE_POSITION_KEY = "pitch_position"

local function after_place_node(pos)
	local meta = core.get_meta(pos)

	meta:set_int(NOTE_POSITION_KEY, #NOTES)
end

local function play_sound(pos)
	local meta = core.get_meta(pos)
	local opts = NOTES[meta:get_int(NOTE_POSITION_KEY)]
	local pitch = opts[1]

	core.sound_play("pyutest_note", {
		pos = pos,
		gain = 0.075, -- It's very loud for some reason.
		pitch = pitch
	})

	math.randomseed(os.time())
	core.add_particle({
		texture = "pyutest-note.png^[multiply:"..opts[2],
		pos = pos + vector.new(0, 1, 0),
		velocity = vector.new(0, 0.45, 0),
		expirationtime = 1,
		size = 2,
		vertical = true,
		glow = core.LIGHT_MAX
	})
end

PyuTest.make_electricity_device("pyutest_electricity:note_block", "Note Block", {
	choppy = PyuTest.BLOCK_FAST
}, {"pyutest-note-block.png"}, nil, {
	after_place_node = after_place_node,
	on_rightclick = function (pos, node, clicker)
		local meta = core.get_meta(pos)
		local ppos = meta:get_int(NOTE_POSITION_KEY)

		if ppos == #NOTES then
			meta:set_int(NOTE_POSITION_KEY, 1)
		else
			meta:set_int(NOTE_POSITION_KEY, ppos + 1)
		end

		play_sound(pos)
	end
}, function (pos, node, sender_pos)
	play_sound(pos)
end)

core.register_abm({
	label = "Note Block infotext",
	nodenames = {"pyutest_electricity:note_block"},
	interval = 1,
	chance = 1,
	action = function (pos)
		local meta = core.get_meta(pos)

		meta:set_string("infotext", string.format("Note: %d", meta:get_int(NOTE_POSITION_KEY)))
	end
})

core.register_craft({
	output = "pyutest_electricity:note_block",
	recipe = {
		{"group:wooden_planks", "group:wooden_planks", "group:wooden_planks"},
		{"group:wooden_planks", "pyutest_ores:copper_ingot", "group:wooden_planks"},
		{"group:wooden_planks", "group:wooden_planks", "group:wooden_planks"},
	}
})
