-- this file contains a few enhancements to the normal book and
-- paper functionality. it allows authors to disavow their books,
-- making them appear as by an "unknown author", by smudging out
-- the byline with black dye. it also allows written books to be
-- soaked in a bucket of water to wash out the ink and return
-- them to a virginal, unwritten state. finally, it makes it so
-- that when a book (or any owned item, for that matter) is
-- copied, the owner of the new copy is set to the user who
-- copied it, allowing users to collaborate on books.

local paperburn = function(item,value)
	minetest.register_craft { type = 'fuel', recipe = item, burntime = 3 * value }
	minetest.register_craft {
		type = 'cooking';
		recipe = item;
		output = 'sorcery:ash ' .. tostring(value);
		cooktime = 3 * value;
	}
end

paperburn('default:paper',1) paperburn('sorcery:recipe',1)
paperburn('default:book',3) paperburn('sorcery:cookbook',3)
paperburn('default:book_written',3)

minetest.register_craft {
	type = "shapeless";
	recipe = {"default:book_written", "bucket:bucket_water"};
	output = "default:book";
	replacements = {
		{"bucket:bucket_water", "bucket:bucket_empty"}
	}
}

minetest.register_craft {
	type = 'shapeless';
	recipe = {"default:book_written", "dye:black"};
	output = 'default:book_written';
}

minetest.register_on_craft(function(itemstack,player,recipe,pinv)
	local meta = itemstack:get_meta()
	if not meta:contains('owner') then return nil end
	local pname = player:get_player_name()
	if meta:get_string('owner') ~= pname then
		meta:set_string('owner', pname)
	end

	if itemstack:get_name() == 'default:book_written' then
		local found_book, found_dye, book_idx = false, false, 0
		for i,v in pairs(recipe) do
			if v:get_name() == 'dye:black' and not found_dye
				then found_dye = true
			elseif v:get_name() == 'default:book_written' and not found_book
				then found_book = v book_idx = i
			elseif not v:is_empty() then found_book = false break end
		end
		if found_book and found_dye then
			meta:from_table(found_book:get_meta():to_table())
			meta:set_string('owner','unknown author')
			meta:set_string('description','"'..meta:get_string('title')..'"')
			pinv:set_stack('craft',book_idx,ItemStack())
		end
	end
	return itemstack
end)
