-- Global farming namespace

farming = {}
farming.path = minetest.get_modpath("farming")


-- Load files

farming.registered_plants = {}


function use_as_hoe(itemstack, clicker,  pointed_thing)
	local name=itemstack:get_name()
	local r= minetest.get_item_group(name, "hoe") 
	if r ~= 0 and clicker and pointed_thing then
		local playerName=clicker:get_player_name()
		itemstack:add_wear(65536/r)
		local pos=pointed_thing.under
		if minetest.get_node(pos).name ~="default:dirt" then
			minetest.chat_send_player(playerName, minetest.registered_nodes[minetest.get_node(pos).name].description)
			return itemstack
		end
		if minetest.is_protected(pos, clicker:get_player_name()) then
			return itemstack
		end

		if not minetest.find_node_near(pos, 1, {"group:water"}) then
			minetest.chat_send_player(playerName, "No water nearby")
			return itemstack
		end
		if (minetest.get_node_light(pointed_thing.above, 0.5) or 0) < 15 then
			minetest.chat_send_player(playerName, "Not enought light")
			return itemstack
		end

		minetest.set_node(pos, {name="farming:soil_wet"})
		minetest.sound_play("default_dig_crumbly", {
			pos = pos,
			gain = 0.5,
		}, true)
	end
	return itemstack
end

local desc="\nRight-click sunlit dirt near water to turn it into a farm plot.\nRight-clicking other blocks will give their description."
minetest.override_item("default:shovel_bronze", { on_place= use_as_hoe, description="Bronze shovel"..desc, groups={hoe=128} })
minetest.override_item("default:shovel_steel", { on_place= use_as_hoe, description="Steel shovel"..desc, groups={hoe=512}  })

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

	local under = minetest.get_node(pt.under)
	local above = minetest.get_node(pt.above)

	local player_name = placer and placer:get_player_name() or ""

	if minetest.is_protected(pt.under, player_name) then
		minetest.record_protection_violation(pt.under, player_name)
		return itemstack
	end
	if minetest.is_protected(pt.above, player_name) then
		minetest.record_protection_violation(pt.above, player_name)
		return itemstack
	end

	-- check if pointing at the top of the node
	if pt.above.y ~= pt.under.y+1 then return itemstack end

	-- check if you can replace the node above the pointed node
	if not minetest.registered_nodes[above.name].buildable_to then
		return itemstack
	end

	-- check if pointing at soil
	if under.name ~= "farming:soil_wet" then
		return itemstack
	end

	minetest.add_node(pt.above, {name = plantname, param2 = 1})
	-- minetest.get_node_timer(pt.above):start(3600+math.random(-180,180)) -- 1H +- 10%
	default.start_grow_timer(3600, pt.above, biome)
	itemstack:take_item()
	return itemstack
end

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

	-- grow seed
	if minetest.get_item_group(node.name, "seed") then
		minetest.set_node(pos, {name=def.next_plant})
	end
end

local reverse_soil=function(pos)
   local under={x=pos.x, y=pos.y-1, z=pos.z}
   if minetest.get_node(under).name=="farming:soil_wet" then
	   minetest.set_node(under, {name="dirt"})
   end
end

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

	-- Check def table
	if not def.description then def.description = "Seed" end
	if not def.inventory_image then def.inventory_image = "unknown_item.png" end

	farming.registered_plants[pname] = def

	-- Register seed
	minetest.register_node(":" .. mname .. ":seed_" .. pname, {
		description = def.description.." seed",
		tiles = {def.inventory_image},
		inventory_image = def.inventory_image,
		wield_image = def.inventory_image,
		drawtype = "signlike",
		groups = {seed = 1, snappy = 3, attached_node = 1, flammable = 2},
		paramtype = "light",
		paramtype2 = "wallmounted",
		walkable = false,
		sunlight_propagates = true,
		selection_box = {
			type = "fixed",
			fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5},
		},
		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 under = pointed_thing.under
			local node = minetest.get_node(under)
			local udef = minetest.registered_nodes[node.name]
			if udef and udef.on_rightclick and
					not (placer and placer:is_player() and
					placer:get_player_control().sneak) then
				return udef.on_rightclick(under, node, placer, itemstack,
					pointed_thing) or itemstack
			end

			local biome= pname=="wheat" and "deciduous_forest" or "savanna"
			return farming.place_seed(itemstack, placer, pointed_thing, mname .. ":seed_" .. pname, biome)
		end,
		after_dig_node=reverse_soil,
		next_plant = mname .. ":" .. pname,
		on_timer = farming.grow_plant,
	})

	-- register harvest
	minetest.register_craftitem(":" .. mname .. ":" .. pname, {
		description = def.description:gsub("^%l", string.upper),
		inventory_image = mname .. "_" .. pname .. "_8.png",
		groups = def.groups or {flammable = 2},
	})

	-- Register plant
	minetest.register_node(":" .. mname .. ":" .. pname, {
		drawtype = "plantlike",
		description=def.description,
		waving = 1,
		tiles = {mname .. "_" .. pname .. "_8.png"},
		paramtype = "light",
		paramtype2 = def.paramtype2 or nil,
		place_param2 = def.place_param2 or nil,
		walkable = false,
		buildable_to = true,
		drop =
		{
			items = {
				{items = {mname .. ":seed_" .. pname}, rarity = 2},
				{items = {mname .. ":" .. pname}, rarity = 1},
			}
		},
		selection_box = {
			type = "fixed",
			fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5},
		},
		groups = {snappy = 3, flammable = 2, plant = 1, attached_node = 1},
		sounds = default.node_sound_leaves_defaults(),
		on_timer = farming.grow_plant,
		after_dig_node=reverse_soil,
		on_place=function() return nil end
	})
end

minetest.register_node("farming:soil_wet", {
	description = "Wet Soil",
	tiles = {"default_dirt.png^farming_soil_wet.png", "default_dirt.png^farming_soil_wet_side.png"},
	drop = "default:dirt",
	groups = {crumbly=1, not_in_creative_inventory=1, soil=3, wet = 1, grassland = 1, field = 1},
	sounds = default.node_sound_dirt_defaults(),
})


minetest.register_node("farming:straw", {
	description = "Straw",
	tiles = {"farming_straw.png"},
	is_ground_content = false,
	groups = {snappy=2, flammable=4, fall_damage_add_percent=-30},
	sounds = default.node_sound_leaves_defaults(),
	drop="stairs:stair_straw 4",
})

-- WHEAT

farming.register_plant("farming:wheat", {
	description = "Wheat",
	paramtype2 = "meshoptions",
	inventory_image = "farming_wheat_seed.png",
	groups = {food_wheat = 1, flammable = 4},
	place_param2 = 3,
})

minetest.register_craftitem("farming:flour", {
	description = "Flour",
	inventory_image = "farming_flour.png",
	groups = {food_flour = 1, flammable = 1},
})

minetest.register_craftitem("farming:bread", {
	description = "Bread",
	inventory_image = "farming_bread.png",
	on_use = minetest.item_eat(5),
	groups = {food_bread = 1, flammable = 2, heal=5},
})

minetest.register_craft({
	type = "shapeless",
	output = "farming:flour",
	recipe = {"farming:wheat", "farming:wheat", "farming:wheat", "farming:wheat", "flowers:mushroom_brown", "flowers:mushroom_brown"}
})

minetest.register_craft({
	type = "cooking",
	cooktime = 15,
	output = "farming:bread",
	recipe = "farming:flour"
})

-- Cotton

farming.register_plant("farming:cotton", {
	description = "Cotton",
	inventory_image = "farming_cotton_seed.png",
	groups = {flammable = 4},
})

minetest.register_craftitem("farming:string", {
	description = "String",
	inventory_image = "farming_string.png",
	groups = {flammable = 2},
})

minetest.register_craft({
	output = "farming:string",
	type="shapeless",
	recipe = {"farming:cotton", "farming:cotton","farming:cotton", "farming:cotton", "default:mese_crystal_fragment"},
	
})

minetest.register_craft({
	type="shapeless",
	output = "farming:straw",
	recipe = {"group:leaves","group:leaves","group:leaves","group:leaves","group:leaves","group:leaves","group:leaves","group:leaves","group:leaves",}
})


stairs.register_stair_and_slab(
	"straw",
	"farming:straw",
	{snappy=2, flammable=4, fall_damage_add_percent=-30},
	{"farming_straw.png"},
	"Straw Stair",
	"Straw Slab",
	default.node_sound_leaves_defaults(),
	false
)

-- Fuels

minetest.register_craft({
	type = "fuel",
	recipe = "farming:straw",
	burntime = 7,
})

-- See "Soda process", which is one of the first chemical process to produce paper (19th century).
-- It let produce paper from wheat straw. Our straw is made from leaves, though, but the chemicals are replaced
-- by mese anyway.

minetest.register_craft {
	type="shapeless",
	output="default:paper",
	recipe={"default:mese_crystal_fragment", "farming:straw", "farming:straw", "farming:straw", "farming:straw", "farming:straw", "farming:straw", "farming:straw", "farming:straw"}
}

-- Compatibility with original mod
-- Most are useless and deprecated...
minetest.register_alias("farming:hoe_wood", "default:shovel_bronze")
minetest.register_alias("farming:hoe_stone", "default:shovel_bronze")
minetest.register_alias("farming:hoe_steel", "default:shovel_bronze")
minetest.register_alias("farming:hoe_bronze", "default:shovel_bronze")
minetest.register_alias("farming:hoe_mese", "default:shovel_bronze")
minetest.register_alias("farming:hoe_diamond", "default:shovel_bronze")
minetest.register_alias("farming:dry_soil", "farming:soil")
-- minetest.register_oxymoron()...
minetest.register_alias("farming:dry_soil_wet", "farming:soil_wet")
minetest.register_alias("farming:desert_sand_soil", "farming:soil")
minetest.register_alias("farming:desert_sand_soil_wet", "farming:soil_wet")


farming.register_hoe = function(name, def)
	if name:sub(1,1) ~= ":" then name = ":" .. name end
	minetest.register_tool(name, {
		description = def.description or "Hoe",
		inventory_image = def.inventory_image or "unknown_item.png",
		on_place = use_as_hoe,
		groups = def.groups,
		sound = {breaks = "default_tool_breaks"},
	})
	if def.recipe then
		minetest.register_craft{
			output = name:sub(2),
			recipe = def.recipe
		}
	elseif def.material then
		minetest.register_craft{
			output = name:sub(2),
			recipe = {
				{def.material, def.material},
				{"", "group:stick"},
				{"", "group:stick"}
			}
		}
	end
end
