local S = minetest.get_translator("default")

-- List of sound handles for active furnace
local fermenter_fire_sounds = {}

--
-- Formspecs
--

function technic_farming.get_fermenter_active_formspec(item_percent)
	return "size[8,8.5]"..
		"list[context;src;2.75,0.5;1,1;]"..
		"image[3.75,1.5;1,1;gui_furnace_arrow_bg.png^[lowpart:"..
		(item_percent)..":gui_furnace_arrow_fg.png^[transformR270]"..
		"list[context;dst;4.75,0.96;2,2;]"..
		"list[current_player;main;0,4.25;8,1;]"..
		"list[current_player;main;0,5.5;8,3;8]"..
		"listring[context;dst]"..
		"listring[current_player;main]"..
		"listring[context;src]"..
		"listring[current_player;main]"..
		"listring[context;fuel]"..
		"listring[current_player;main]"..
		default.get_hotbar_bg(0, 4.25)
end

function technic_farming.get_fermenter_inactive_formspec()
	return "size[8,8.5]"..
		"list[context;src;2.75,0.5;1,1;]"..
		"image[3.75,1.5;1,1;gui_furnace_arrow_bg.png^[transformR270]"..
		"list[context;dst;4.75,0.96;2,2;]"..
		"list[current_player;main;0,4.25;8,1;]"..
		"list[current_player;main;0,5.5;8,3;8]"..
		"listring[context;dst]"..
		"listring[current_player;main]"..
		"listring[context;src]"..
		"listring[current_player;main]"..
		"listring[context;fuel]"..
		"listring[current_player;main]"..
		default.get_hotbar_bg(0, 4.25)
end

local function stop_fermenter_sound(pos, fadeout_step)
	local hash = minetest.hash_node_position(pos)
	local sound_ids = fermenter_fire_sounds[hash]
	if sound_ids then
		for _, sound_id in ipairs(sound_ids) do
			minetest.sound_fade(sound_id, -1, 0)
		end
		fermenter_fire_sounds[hash] = nil
	end
end

local function fermenter_node_timer(pos, elapsed)
	--
	-- Initialize metadata
	--
	local meta = minetest.get_meta(pos)
	local src_time = meta:get_float("src_time") or 0

	local inv = meta:get_inventory()
	local srclist
	local dst_full = false
	local full_flow = 120
	local timer_elapsed = meta:get_int("timer_elapsed") or 0
	meta:set_int("timer_elapsed", timer_elapsed + 1)


	-- ensure that grinding with mp machines are slower than with electric machines
	local rel_time = 1
	local update = true
	local fermentable
	local fermenttime = 0

	while elapsed > 0 and update do
		update = false

		srclist = inv:get_list("src")

		-- Check if we have grindable content
		local fermented = technic.get_recipe("ferment",srclist)
		print(fermented)
		fermenttime = 0
		local fermentoutput
		if fermented then
			fermenttime = fermented.time or 0
			fermentoutput = string.split(fermented.output,' ')[1]
			if(srclist[1]:get_count() > 0 and minetest.registered_items[fermentoutput] and fermenttime == 0) then
				fermenttime = 1
			end
		end
		
		fermentable = fermenttime ~= 0
		if fermentable then 
			src_time = src_time + rel_time

			if src_time >= fermenttime then
				-- Place result in dst list if possible
				if inv:room_for_item("dst", fermentoutput) then
					inv:add_item("dst", fermented.output)
					inv:set_stack("src",1,fermented.new_input[1])
					src_time = src_time - fermenttime
					update = true
				else
					dst_full = true
				end
				-- Play cooling sound
				minetest.sound_play("default_cool_lava",
					{pos = pos, max_hear_distance = 16, gain = 0.07}, true)
			else
				-- Item could not be cooked: probably missing fuel
				update = true
			end
		
		end
		elapsed = elapsed - 1
	end

	if srclist and srclist[1]:is_empty() then
		src_time = 0
	end

	--
	-- Update formspec, infotext and node
	--
	local formspec
	local item_state
	local item_percent = 0
	if fermentable then
		item_percent = math.floor(src_time / fermenttime * 100)
		if dst_full then
			item_state = S("100% (output full)")
		else
			item_state = S("@1%", item_percent)
		end
	else
		if srclist and not srclist[1]:is_empty() then
			item_state = S("Not fermentable")
		else
			item_state = S("Empty")
		end
	end

	local fuel_state = S("Empty")
	local active = false
	local result = false

	if src_time ~= 0 then
--	if false then
		active = true
		local fuel_percent = rel_time
		fuel_state = S("@1%", fuel_percent)
		formspec = technic_farming.get_fermenter_active_formspec(item_percent)
		technic_farming.swap_node(pos, "technic_farming:fermenter_active")
		-- make sure timer restarts automatically
		result = true

		-- Play sound every 5 seconds while the furnace is active
		if timer_elapsed == 0 or (timer_elapsed + 1) % 5 == 0 then
			local sound_id = minetest.sound_play("technic_farming:fermenter_active",
				{pos = pos, max_hear_distance = 16, gain = 0.25})
			local hash = minetest.hash_node_position(pos)
			fermenter_fire_sounds[hash] = fermenter_fire_sounds[hash] or {}
			table.insert(fermenter_fire_sounds[hash], sound_id)
			-- Only remember the 3 last sound handles
			if #fermenter_fire_sounds[hash] > 3 then
				table.remove(fermenter_fire_sounds[hash], 1)
			end
			-- Remove the sound ID automatically from table after 11 seconds
			minetest.after(11, function()
				if not fermenter_fire_sounds[hash] then
					return
				end
				for f=#fermenter_fire_sounds[hash], 1, -1 do
					if fermenter_fire_sounds[hash][f] == sound_id then
						table.remove(fermenter_fire_sounds[hash], f)
					end
				end
				if #fermenter_fire_sounds[hash] == 0 then
					fermenter_fire_sounds[hash] = nil
				end
			end)
		end
	else
		formspec = technic_farming.get_fermenter_inactive_formspec()
		technic_farming.swap_node(pos, "technic_farming:fermenter")
		-- stop timer on the inactive furnace
		minetest.get_node_timer(pos):stop()
		meta:set_int("timer_elapsed", 0)

		stop_fermenter_sound(pos)
	end


	local infotext
	if active then
		infotext = S("Fermenter active")
	else
		infotext = S("Fermenter inactive")
	end
	infotext = infotext .. "\n" .. S("(Item: @1)", item_state)

	--
	-- Set meta values
	--
	meta:set_float("src_time", src_time)
	meta:set_string("formspec", formspec)
	meta:set_string("infotext", infotext)

	return result
end

--
-- Node definitions
--

minetest.register_node("technic_farming:fermenter", {
	description = S("Fermenter"),
	tiles = {
		"technic_farming_fermenter_bottom.png",
		"technic_farming_fermenter_bottom.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_front.png"
	},
	paramtype2 = "facedir",
	groups = {cracky=2},
	legacy_facedir_simple = true,
	is_ground_content = false,
	sounds = default.node_sound_stone_defaults(),

	can_dig = technic_farming.can_dig,

	on_timer = fermenter_node_timer,

	on_construct = function(pos)
		local meta = minetest.get_meta(pos)
		local inv = meta:get_inventory()
		inv:set_size('src', 1)
		inv:set_size('dst', 4)
		fermenter_node_timer(pos, 0)
	end,

	on_metadata_inventory_move = function(pos)
		minetest.get_node_timer(pos):start(1.0)
	end,
	on_metadata_inventory_put = function(pos)
		-- start timer function, it will sort out whether furnace can burn or not.
		minetest.get_node_timer(pos):start(1.0)
	end,
	on_metadata_inventory_take = function(pos)
		-- check whether the furnace is empty or not.
		minetest.get_node_timer(pos):start(1.0)
	end,
	on_blast = function(pos)
		local drops = {}
		default.get_inventory_drops(pos, "src", drops)
--		default.get_inventory_drops(pos, "fuel", drops)
		default.get_inventory_drops(pos, "dst", drops)
		drops[#drops+1] = "technic_farming:fermenter"
		minetest.remove_node(pos)
		return drops
	end,

	allow_metadata_inventory_put = technic_farming.allow_metadata_inventory_put,
	allow_metadata_inventory_move = technic_farming.allow_metadata_inventory_move,
	allow_metadata_inventory_take = technic_farming.allow_metadata_inventory_take,
})

minetest.register_node("technic_farming:fermenter_active", {
	description = S("Fermenter"),
	tiles = {
		"technic_farming_fermenter_bottom.png",
		"technic_farming_fermenter_bottom.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_side.png",
		"technic_farming_fermenter_front.png"
	},
	paramtype2 = "facedir",
	light_source = 8,
	drop = "technic_farming:fermenter",
	groups = {cracky=2, not_in_creative_inventory=1},
	legacy_facedir_simple = true,
	is_ground_content = false,
	sounds = default.node_sound_stone_defaults(),
	on_timer = fermenter_node_timer,
	on_destruct = function(pos)
		stop_fermenter_sound(pos)
	end,

	can_dig = technic_farming.can_dig,

	allow_metadata_inventory_put = technic_farming.allow_metadata_inventory_put,
	allow_metadata_inventory_move = technic_farming.allow_metadata_inventory_move,
	allow_metadata_inventory_take = technic_farming.allow_metadata_inventory_take,
})

minetest.register_craft({
	output = 'technic_farming:fermenter',
	recipe = {
		{'group:wood', 'technic_farming:wooden_plate', 'group:wood'},
		{'group:wood', '',                             'group:wood'},
		{'group:wood', 'technic_farming:wooden_plate', 'group:wood'},
	}
})
