local S, log = ...

farming.registered_plants = {}
farming.registered_hoes = {}

-- Wear out hoes, place soil
function farming.hoe_on_use(itemstack, user, pointed_thing, uses)
	-- Support old `pos` usage for the 3rd parameter
	if pointed_thing.x and pointed_thing.y and pointed_thing.z then
		log:warning("passing vector as 3rd parameter to farming.hoe_on_use is deprecated, should be pointed thing instead")
		local pos = vector.copy(pointed_thing)
		pointed_thing = {
			type = "node",
			under = pos,
			--above = pos:offset(0, 1, 0),
		}
	end

	-- Check if pointing at a node
	if pointed_thing.type ~= "node" then
		return itemstack
	end

	local under = core.get_node(pointed_thing.under)
	local p = vector.offset(pointed_thing.under, 0, 1, 0)
	local above = core.get_node(p)

	-- Return if any of the nodes is not registered
	local def = core.registered_nodes[under.name]
	if not def then return end
	local def_above = core.registered_nodes[above.name]
	if not def_above then return end

	-- Check if the node above the pointed thing is OK
	if def_above.walkable or not def_above.sunlight_propagates then return end

	-- Check if pointing at soil
	if core.get_item_group(under.name, "soil") ~= 1 then return end

	-- Check if (wet) soil defined
	if def.soil == nil or def.soil.wet == nil or def.soil.dry == nil then return end

	-- Check for protection
	local player_name = user and user:get_player_name() or ""
	if core.is_protected(pointed_thing.under, player_name) then
		core.record_protection_violation(pointed_thing.under, player_name)
		return
	end
	if core.is_protected(pointed_thing.above, player_name) then
		core.record_protection_violation(pointed_thing.above, player_name)
		return
	end

	-- Turn the node into soil and play sound
	core.set_node(pointed_thing.under, {name = def.soil.dry})
	core.sound_play("default_dig_crumbly", {
		pos = pointed_thing.under,
		gain = 0.3,
	}, true)

	if not core.is_creative_enabled(player_name) then
		-- Wear tool
		itemstack:add_wear_by_uses(uses)
		-- Tool break sound
		local wdef = itemstack:get_definition()
		if itemstack:get_count() == 0 and wdef.sound and wdef.sound.breaks then
			core.sound_play(wdef.sound.breaks, {pos = pointed_thing.above, gain = 0.5}, true)
		end
	end
	return itemstack
end

-- Register new hoes
function farming.register_hoe(name, def)
	-- Check for : prefix (register new hoes in your mod's namespace)
	if name:sub(1,1) ~= ":" then
		name = ":" .. name
	end

	def.max_uses = def.max_uses or 30

	farming.registered_hoes[name] = def

	local tdef = {}
	tdef.description = def.description or S("Hoe")
	tdef.inventory_image = def.inventory_image
	tdef.groups = table.update({hoe = 1}, def.groups)
	tdef.on_place = def.on_place or function(itemstack, user, pointed_thing)
		local rc = voxelgarden.call_on_rightclick(itemstack, user, pointed_thing)
		return rc or farming.hoe_on_use(itemstack, user, pointed_thing, def.max_uses)
	end

	-- Register the tool
	core.register_tool(name, table.update({
		sound = default.tool_sound_pick_defaults()
	}, tdef))

	-- Register its recipe
	if def.recipe then
		core.register_craft({
			output = name:sub(2),
			recipe = def.recipe
		})
	elseif def.material then
		core.register_craft({
			output = name:sub(2),
			recipe = {
				{def.material, def.material},
				{"", "group:stick"},
				{"", "group:stick"}
			}
		})
	end
end

-- How often node timers for plants will tick, +/- some random value
local function tick(pos)
	core.get_node_timer(pos):start(math.random(126, 246))
end
-- How often a growth failure tick is retried (e.g. too dark)
local function tick_again(pos)
	core.get_node_timer(pos):start(math.random(24, 48))
end

-- Seed placement
function farming.place_seed(itemstack, placer, pointed_thing, plantname)
	-- Check if pointing at a node
	if pointed_thing.type ~= "node" then
		return itemstack
	end

	local under = core.get_node(pointed_thing.under)
	local above = core.get_node(pointed_thing.above)

	-- Check for protection
	local player_name = placer and placer:get_player_name() or ""
	if core.is_protected(pointed_thing.under, player_name) then
		core.record_protection_violation(pointed_thing.under, player_name)
		return
	end
	if core.is_protected(pointed_thing.above, player_name) then
		core.record_protection_violation(pointed_thing.above, player_name)
		return
	end

	-- Return if any of the nodes is not registered
	local def_above = core.registered_nodes[above.name]
	if not core.registered_nodes[under.name] then return itemstack end
	if not def_above then return end

	-- Check if pointing at the top of the node
	if pointed_thing.above.y ~= (pointed_thing.under.y + 1) then return end

	-- Check if you can replace the node above the pointed node
	if not def_above.buildable_to then return end

	-- Check if pointing at soil
	if core.get_item_group(under.name, "soil") < 2 then return end

	-- Log action
	if placer then
		default.log_player_action(placer, "places node", plantname, "at", pointed_thing.above)
	end
	-- Add node
	core.set_node(pointed_thing.above, {name = plantname, param2 = 1})
	-- Start timer
	tick_again(pointed_thing.above)

	if not core.is_creative_enabled(player_name) then
		itemstack:take_item()
	end
	return itemstack
end

-- Check if on wet soil
function farming.can_grow(pos)
	local below = core.get_node(vector.offset(pos, 0, -1, 0))
	return core.get_item_group(below.name, "soil") >= 3
end

function farming.grow_plant(pos, elapsed)
	local node = core.get_node(pos)
	local name = node.name
	local def = core.registered_nodes[name]

	if not def.next_plant then
		-- Disable timer for fully grown plant
		return
	end

	-- Grow seed
	if core.get_item_group(node.name, "seed") and def.fertility then
		local soil_node = core.get_node_or_nil(vector.offset(pos, 0, -1, 0))
		if not soil_node then
			return tick_again(pos)
		end
		-- omitted is a check for light, we assume seeds can germinate in the dark.
		for _, v in ipairs(def.fertility) do
			if core.get_item_group(soil_node.name, v) ~= 0 then
				local placenode = {name = def.next_plant}
				if def.place_param2 then
					placenode.param2 = def.place_param2
				end
				core.swap_node(pos, placenode)
				if core.registered_nodes[def.next_plant].next_plant then
					return tick(pos)
				end
			end
		end

		return
	end

	if not (def.can_grow or farming.can_grow)(pos) then
		return tick_again(pos)
	end

	do -- Check light
		local light = core.get_node_light(pos)
		if not light or light < def.minlight or light > def.maxlight then
			return tick_again(pos)
		end
	end

	do -- Grow
		local placenode = {name = def.next_plant}
		if def.place_param2 then
			placenode.param2 = def.place_param2
		end
		core.swap_node(pos, placenode)
	end

	-- New timer needed?
	if core.registered_nodes[def.next_plant].next_plant then
		return tick(pos)
	end
end

-- Register plants
function farming.register_plant(name, def)
	local mname, pname; do
		local split = name:split(":")
		mname, pname = split[1], split[2]
	end

	-- Check def table
	def.description = def.description or S("Seed")
	def.harvest_description = def.harvest_description or pname:gsub("^%l", string.upper)
	if not def.steps then return end
	def.minlight = def.minlight or 1
	def.maxlight = def.maxlight or default.LIGHT_MAX
	def.fertility = def.fertility or {}

	farming.registered_plants[pname] = def

	-- Register seed
	local lbm_nodes = {}
	local g = {seed = 1, snappy = 3, attached_node = 1, flammable = 2}
	for k, v in pairs(def.fertility) do
		g[v] = 1
	end
	core.register_node(":" .. mname .. ":seed_" .. pname, table.update({
		description = def.description,
		tiles = {def.inventory_image},
		inventory_image = def.inventory_image,
		wield_image = def.inventory_image,
		drawtype = "signlike",
		groups = g,
		paramtype = "light",
		paramtype2 = "wallmounted",
		place_param2 = def.place_param2 or nil, -- this isn't actually used for placement
		walkable = false,
		sunlight_propagates = true,
		selection_box = {type = "wallmounted"},
		fertility = def.fertility,
		sounds = default.node_sound_dirt_defaults({
			dig = {name = "", gain = 0},
			dug = {name = "default_grass_footstep", gain = 0.2},
			place = {name = "default_place_node", gain = 0.25},
		}),

		on_place = function(itemstack, placer, pointed_thing)
			local rc = voxelgarden.call_on_rightclick(itemstack, placer, pointed_thing)
			return rc or farming.place_seed(itemstack, placer, pointed_thing, mname .. ":seed_" .. pname)
		end,
		next_plant = mname .. ":" .. pname .. "_1",
		on_timer = farming.grow_plant,
		minlight = def.minlight,
		maxlight = def.maxlight,
	}, def.override))

	-- Register harvest
	core.register_craftitem(":" .. mname .. ":" .. pname, {
		description = def.harvest_description,
		inventory_image = mname .. "_" .. pname .. ".png",
		groups = def.groups or {flammable = 2},
	})

	-- Register growing steps
	for i = 1, def.steps do
		local base_rarity = 1
		if def.steps ~= 1 then
			base_rarity =  8 - (i - 1) * 7 / (def.steps - 1)
		end
		local drop = {
			items = {
				{items = {mname .. ":" .. pname}, rarity = base_rarity},
				{items = {mname .. ":" .. pname}, rarity = base_rarity * 2},
				{items = {mname .. ":seed_" .. pname}, rarity = base_rarity},
				{items = {mname .. ":seed_" .. pname}, rarity = base_rarity * 2},
			}
		}

		local nodegroups = {snappy = 3, flammable = 2, plant = 1, not_in_creative_inventory = 1, attached_node = 1}
		nodegroups[pname] = i

		local height = 0.5 - 0.25 * (def.steps - i)

		local sdef = {
			drawtype = "plantlike",
			waving = 1,
			tiles = {mname .. "_" .. pname .. "_" .. i .. ".png"},
			paramtype = "light",
			paramtype2 = def.paramtype2,
			place_param2 = def.place_param2,
			walkable = false,
			buildable_to = true,
			drop = drop,
			selection_box = {
				type = "fixed",
				fixed = {-7/16, -8/16, -7/16, 7/16, height, 7/16},
			},
			groups = nodegroups,
			sounds = default.node_sound_leaves_defaults(),
			on_timer = farming.grow_plant,
			minlight = def.minlight,
			maxlight = def.maxlight,
		}

		if i < def.steps then
			sdef.next_plant = mname .. ":" .. pname .. "_" .. (i + 1)
			lbm_nodes[#lbm_nodes + 1] = mname .. ":" .. pname .. "_" .. i
		elseif def.regrow then
			-- Turn into stage 1 when harvested
			sdef.after_dig_node = function(pos)
				core.swap_node(pos, {name = mname .. ":" .. pname .. "_1"})
				tick(pos)
			end
		end


		core.register_node(":" .. mname .. ":" .. pname .. "_" .. i, sdef)
	end

	-- Replacement LBM for pre-nodetimer plants
	core.register_lbm({
		name = ":" .. mname .. ":start_nodetimer_" .. pname,
		nodenames = lbm_nodes,
		action = tick,
	})

	return {
		seed = mname .. ":seed_" .. pname,
		harvest = mname .. ":" .. pname,
		mature = mname .. ":" .. pname .. "_" .. def.steps
	}
end
