-- Crafting Mod - semi-realistic crafting in minetest
-- Copyright (C) 2018 rubenwardy <rw@rubenwardy.com>
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

crafting.register_type("inv")

local player_inv_hashes = {}

local function check_for_changes()
   for _, player in pairs(minetest.get_connected_players() or {}) do
      if sfinv.get_or_create_context(player).page == "sfinv:crafting" then
	 local hash = crafting.calc_inventory_list_hash(player:get_inventory(), "main")
	 local old_hash = player_inv_hashes[player:get_player_name()]
	 if hash ~= old_hash then
	    sfinv.set_page(player, "sfinv:crafting")
	 end
      end
   end

   minetest.after(1, check_for_changes)
end


if minetest.global_exists("sfinv") then

	local trash = minetest.create_detached_inventory("crafting_trash", {
		-- Allow the stack to be placed and remove it in on_put()
		-- This allows the creative inventory to restore the stack
		allow_put = function(inv, listname, index, stack, player)
		   --#TODO: allow trashing empty backpacks?
		   if not string.match(stack:get_name(), "backpacks:") then
		      return stack:get_count()
		   end
		   return 0
		end,
		on_put = function(inv, listname)
			inv:set_list(listname, {})
		end,
	})
	trash:set_size("main", 1)

	sfinv.override_page("sfinv:crafting", {
		get = function(self, player, context)
			player_inv_hashes[player:get_player_name()] =
					crafting.calc_inventory_list_hash(player:get_inventory(), "main")

			local formspec = crafting.make_result_selector(player, "inv", 1, { x = 8, y = 3 }, context)
			formspec = formspec .. "list[detached:crafting_trash;main;0,7.4;1,1;]" ..
					"image[0.05,7.5;0.8,0.8;crafting_trash_icon.png]"
			return sfinv.make_formspec(player, context, formspec, true)
		end,
		on_player_receive_fields = function(self, player, context, fields)
			if crafting.result_select_on_receive_results(player, "inv", 1, context, fields) then
				sfinv.set_player_inventory_formspec(player)
			end
			return true
		end
	})

	minetest.after(1, check_for_changes)
end
