local S = minetest.get_translator("hades_waterplants")

local has_screwdriver = minetest.get_modpath("screwdriver") ~= nil

-- This file supplies seaweed and waterlilies

hades_waterplants = {}


local SPAWN_DELAY = 1000
local SPAWN_CHANCE = 200
local WATERPLANTS_SEED_DIFF = 329
local WATERPLANTS_SEED_DIFF2 = 459
local WATERLILY_FLOWER_MIN_LIGHT = 8

-- register the various rotations of waterlilies


local lilies_list = {
	{ nil  , nil 	 , true },
	{ "225", "22.5"  , true },
	{ "45" , "45"    , true },
	{ "675", "67.5"  , true },
	{ nil  , nil 	 , false },
	{ "225", "22.5"  , false },
	{ "45" , "45"    , false },
	{ "675", "67.5"  , false },
}

local get_random_plant = function(basename, plant_table)
	local r = math.random(1, #plant_table)
	local append = plant_table[r][1]
	local nodename = basename
	if append then
		nodename = nodename .. "_" ..append
	end
	return nodename
end

local node_is_owned = function(pos, placer)
	local name = placer:get_player_name()
	local is_protected = minetest.is_protected(pos, name) and not minetest.check_player_privs(name, "protection_bypass")
	if is_protected then
		minetest.record_protection_violation(pos, name)
		return true
	else
		return false
	end
end

local generate_on_place = function(basename, plant_table)
	return function(itemstack, placer, pt)
		local place_pos = nil
		local top_pos = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z}
		local under_node = minetest.get_node(pt.under)
		local above_node = minetest.get_node(pt.above)
		local top_node   = minetest.get_node(top_pos)
		local udef = minetest.registered_nodes[under_node.name]
		local adef = minetest.registered_nodes[above_node.name]
		local tdef = minetest.registered_nodes[top_node.name]

		if udef and udef.on_rightclick and
			((not placer) or (placer and not placer:get_player_control().sneak)) then
			return udef.on_rightclick(pt.under, under_node, placer, itemstack,
				pt) or itemstack
		end

		if udef and udef.buildable_to then
			if under_node.name ~= "hades_core:water_source" then
				place_pos = pt.under
			elseif top_node.name ~= "hades_core:water_source" and tdef and tdef.buildable_to then
				place_pos = top_pos
			else
				return itemstack
			end
		elseif adef and adef.buildable_to then
			place_pos = pt.above
		end
		if not place_pos then
			return itemstack
		end
		local below_pos = {x=place_pos.x, y=place_pos.y-1, z=place_pos.z}
		local below_node = minetest.get_node(below_pos)
		local bdef = minetest.registered_nodes[below_node.name]
		if below_node.name ~= "hades_core:water_source" and (bdef and not bdef.walkable) then
			return itemstack
		end

		if not node_is_owned(place_pos, placer) then

			local nodename = itemstack:get_name()
			local param2 = 0
			if placer and placer:is_player() then
				local yaw = placer:get_look_horizontal()
				if yaw > math.pi/4 and yaw <= (math.pi/4)*3 then
					param2 = 3
				elseif yaw > (math.pi/4)*3 and yaw <= (math.pi/4)*5 then
					param2 = 2
				elseif yaw > (math.pi/4)*5 and yaw <= (math.pi/4)*7 then
					param2 = 1
				else
					param2 = 0
				end
			end

			minetest.add_node(place_pos, {name = nodename, param2 = param2 })
			minetest.check_single_for_falling(place_pos)
			local idef = itemstack:get_definition()
			if idef and idef.sounds and idef.sounds.place then
				minetest.sound_play(idef.sounds.place, {pos=place_pos, gain=1}, true)
			end

			if not minetest.is_creative_enabled(placer:get_player_name()) then
				itemstack:take_item()
			end
		end
		return itemstack
	end
end

local on_place_waterlily = generate_on_place("hades_waterplants:waterlily", lilies_list)

for i in ipairs(lilies_list) do
	local deg1 = ""
	local deg1_next = ""
	local deg2 = ""
	local has_flower = lilies_list[i][3]
	local g_flower
	if has_flower then
		g_flower = 1
	end
	local lily_groups = {snappy = 3,flammable=2,waterlily=1,waterlily_flowering=g_flower,falling_node=1,float=1}

	local ll1 = lilies_list[i][1]
	if ll1 ~= nil then
		deg1 = "_"..lilies_list[i][1]
		deg2 = "_"..lilies_list[i][2]
		lily_groups.not_in_creative_inventory = 1
	end
	if i < #lilies_list and lilies_list[i+1][1] then
		deg1_next = "_"..lilies_list[i+1][1]
	else
		deg1_next = ""
	end
	if has_flower then
		mnext = "hades_waterplants:waterlily"..deg1_next
	else
		mnext = "hades_waterplants:waterlily"..deg1_next.."_noflower"
	end

	local on_rotate = "simple"
	if has_screwdriver then
		on_rotate = function(pos, node, user, mode, new_param2)
			if mode == screwdriver.ROTATE_FACE then
				local rot = ""
				if ll1 == nil then
					rot = "_225"
				elseif ll1 == "225" then
					rot = "_45"
				elseif ll1 == "45" then
					rot = "_675"
				elseif ll1 == "675" then
					rot = ""
					node.param2 = (node.param2 + 1) % 4
				else
					return
				end
				if has_flower then
					node.name = "hades_waterplants:waterlily" .. rot
				else
					node.name = "hades_waterplants:waterlily" .. rot .. "_noflower"
				end
				minetest.set_node(pos, node)
				return true
			end
			return false
		end
	end

	local tile1, tile2, append, desc
	if has_flower then
		desc = S("Flowering Waterlily")
		tile1 = "flowers_waterlily"..deg2..".png"
		append = ""
	else
		desc = S("Waterlily")
		tile1 = "hades_waterplants_waterlily"..deg2.."_noflower.png"
		append = "_noflower"
	end
	tile2 = "hades_waterplants_waterlily"..deg2.."_noflower.png^[transformFY"


	minetest.register_node("hades_waterplants:waterlily"..deg1..append, {
		description = desc,
		_tt_help = S("Lives on water").."\n"..
			S("Flowers in spring"),
		drawtype = "nodebox",
		tiles = {
			tile1, tile2, "blank.png",
		},
		use_texture_alpha = "clip",
		inventory_image = tile1,
		wield_image  = tile1,
		sunlight_propagates = true,
		paramtype = "light",
		paramtype2 = "facedir",
		walkable = false,
		groups = lily_groups,
		sounds = hades_sounds.node_sound_leaves_defaults(),
		selection_box = {
			type = "fixed",
			fixed = { -0.5, -0.5, -0.5, 0.5, -7/16, 0.5 },
		},
		node_box = {
			type = "fixed",
			fixed = { -0.5, -0.495, -0.5, 0.5, -0.49, 0.5 },
		},
		buildable_to = true,
		floodable = true,
		liquids_pointable = true,
		drop = "hades_waterplants:waterlily"..append,
		node_placement_prediction = "",

		on_place = on_place_waterlily,
		on_rotate = on_rotate,
		_hades_magic_next = mnext,
	})
end


local on_place_seaweed = generate_on_place("hades_waterplants:seaweed", { { nil } })

minetest.register_node("hades_waterplants:seaweed", {
	description = S("Seaweed"),
	_tt_help = S("Lives on water"),
	drawtype = "nodebox",
	tiles = {
		"flowers_seaweed.png",
		"flowers_seaweed.png^[transformFY",
		"blank.png",
	},
	use_texture_alpha = "clip",
	inventory_image = "flowers_seaweed.png",
	wield_image  = "flowers_seaweed.png",
	sunlight_propagates = true,
	paramtype = "light",
	paramtype2 = "facedir",
	walkable = false,
	groups = {snappy = 3,flammable=2,seaweed=1,falling_node=1,float=1},
	sounds = hades_sounds.node_sound_leaves_defaults(),
	selection_box = {
		type = "fixed",
		fixed = { -0.5, -0.5, -0.5, 0.5, -7/16, 0.5 },
	},
	node_box = {
		type = "fixed",
		fixed = { -0.5, -0.495, -0.5, 0.5, -0.49, 0.5 },
	},
	buildable_to = true,
	floodable = true,
	liquids_pointable = true,
	drop = "hades_waterplants:seaweed",

	node_placement_prediction = "",
	on_place = on_place_seaweed,
	on_rotate = "simple",
})

hades_plantslib.spawn_on_surfaces({
	label = "Spawn waterlilies on water",
	spawn_delay = SPAWN_DELAY/2,
	spawn_plants = {
		"hades_waterplants:waterlily_noflower",
		"hades_waterplants:waterlily_225_noflower",
		"hades_waterplants:waterlily_45_noflower",
		"hades_waterplants:waterlily_675_noflower",
	},
	avoid_radius = 2.5,
	spawn_chance = SPAWN_CHANCE*4,
	spawn_surfaces = {"hades_core:water_source"},
	avoid_nodes = {"group:flower" },
	seed_diff = WATERPLANTS_SEED_DIFF,
	light_min = 9,
	random_facedir = {0,3}
})


hades_plantslib.spawn_on_surfaces({
	label = "Spawn seaweed on water",
	spawn_delay = SPAWN_DELAY*2,
	spawn_plants = {"hades_waterplants:seaweed"},
	spawn_chance = SPAWN_CHANCE*2,
	spawn_surfaces = {"hades_core:water_source"},
	avoid_nodes = {"group:flower" },
	seed_diff = WATERPLANTS_SEED_DIFF2,
	light_min = 4,
	light_max = 10,
	neighbors = {"hades_core:dirt_with_grass"},
	facedir = 1
})

hades_plantslib.spawn_on_surfaces({
	label = "Spawn seaweed on dirt with grass",
	spawn_delay = SPAWN_DELAY*2,
	spawn_plants = {"hades_waterplants:seaweed"},
	spawn_chance = SPAWN_CHANCE*2,
	spawn_surfaces = {"hades_core:dirt_with_grass"},
	avoid_nodes = {"group:flower", "group:grass" },
	seed_diff = WATERPLANTS_SEED_DIFF2,
	light_min = 4,
	light_max = 10,
	neighbors = {"hades_core:water_source"},
	ncount = 1,
	facedir = 1
})

-- crafting recipes!


minetest.register_craft({
	output = 'hades_waterplants:seaweed 3',
	recipe = {{'hades_waterplants:waterlily'},}
})

minetest.register_abm({
	label = "Waterlily decay",
	nodenames = {"group:waterlily"},
	interval = 12,
	chance = 12,
	action = function(pos, node)
		local below = vector.offset(pos, 0, -1, 0)
		local bnode = minetest.get_node(below)
		local ok = false
		local drop = false
		-- Waterlily can only survive on water source
		if bnode.name == "air" then
			-- Drop if in mid-air
			drop = true
		elseif minetest.get_item_group(bnode.name, "water") ~= 0 then
			local bdef = minetest.registered_nodes[bnode.name]
			if bdef.liquidtype == "source" then
				ok = true
			else
				-- drop as item when on water node but not water source
				drop = true
			end
		end
		if not ok then
			minetest.remove_node(pos)
			if drop then
				minetest.add_item(pos, {name="hades_waterplants:waterlily"})
			end
		end
	end,
})

minetest.register_abm({
	label = "Seaweed decay",
	nodenames = {"group:seaweed"},
	interval = 12,
	chance = 12,
	action = function(pos, node)
		local below = vector.offset(pos, 0, -1, 0)
		local bnode = minetest.get_node(below)
		local ok = false
		local drop = false
		-- Seaweed can survive on water source, dirt, clay and fertile sand
		if bnode.name == "air" then
			-- Drop if in mid-air
			drop = true
		elseif minetest.get_item_group(bnode.name, "dirt") ~= 0 then
			ok = true
		elseif minetest.get_item_group(bnode.name, "clay") ~= 0 then
			ok = true
		elseif bnode.name == "hades_core:fertile_sand" then
			ok = true
		elseif minetest.get_item_group(bnode.name, "water") ~= 0 then
			local bdef = minetest.registered_nodes[bnode.name]
			if bdef.liquidtype == "source" then
				ok = true
			else
				-- drop as item when on water node but not water source
				drop = true
			end
		end
		if not ok then
			minetest.remove_node(pos)
			if drop then
				minetest.add_item(pos, {name="hades_waterplants:seaweed"})
			end
		end
	end,
})

minetest.register_abm({
	label = "Waterlily flower growth or decay",
	nodenames = {"group:waterlily"},
	interval = 26,
	chance = 25,
	action = function(pos, node)
		-- Waterlilies flower if:
		-- * Light level at least WATERLILY_FLOWER_MIN_LIGHT
		-- * Placed on water source
		-- * It's spring
		local has_flower = minetest.get_item_group(node.name, "waterlily_flowering") ~= 0
		local new_flower_state = has_flower

		local light = minetest.get_node_light(pos)
		if light < WATERLILY_FLOWER_MIN_LIGHT then
			new_flower_state = false
		else
			local below = vector.offset(pos, 0, -1, 0)
			local bnode = minetest.get_node(below)
			local on_water = bnode.name == "hades_core:water_source"
			if not on_water then
				new_flower_state = false
			else
				local season = hades_seasons.get_season()
				new_flower_state = season == hades_seasons.SEASON_SPRING
			end
		end
		if has_flower ~= new_flower_state then
			local newname
			if new_flower_state == true then
				-- Remove "_noflower" suffix
				-- (we assume that only waterlily nodes with or without that suffix exist,
				-- and that no other suffixes exist)
				newname = string.sub(node.name, 1, -10)
			else
				-- Add suffix
				newname = node.name .. "_noflower"
			end
			minetest.set_node(pos, {name = newname, param2 = node.param2})
		end
	end
})


minetest.register_craft({
	type = "fuel",
	recipe = "group:waterlily",
	burntime = 1,
})
minetest.register_craft({
	type = "fuel",
	recipe = "group:seaweed",
	burntime = 1,
})

minetest.register_alias("hades_waterplants:seaweed_2", "hades_waterplants:seaweed")
minetest.register_alias("hades_waterplants:seaweed_3", "hades_waterplants:seaweed")
minetest.register_alias("hades_waterplants:seaweed_4", "hades_waterplants:seaweed")
minetest.register_alias("hades_waterplants:waterlily_s1", "hades_waterplants:waterlily")
minetest.register_alias("hades_waterplants:waterlily_s2", "hades_waterplants:waterlily")
minetest.register_alias("hades_waterplants:waterlily_s3", "hades_waterplants:waterlily")
minetest.register_alias("hades_waterplants:waterlily_s4", "hades_waterplants:waterlily")


minetest.log("action", "[hades_waterplants] loaded.")
