local modname = minetest.get_current_modname()
local modpath = minetest.get_modpath(modname)
local S = minetest.get_translator(modname)

--localize stuff for performance
local random = math.random
local spawn_tree = minetest.spawn_tree
local get_node_timer = minetest.get_node_timer
local remove_node = minetest.remove_node
local place_schematic = minetest.place_schematic

local schematics =
{
	modpath .. "/schematics/little_tree.mts",
	modpath .. "/schematics/palm_tree.mts",
	modpath .. "/schematics/spruce.mts",
	modpath .. "/schematics/tree1.mts",
	modpath .. "/schematics/tree2.mts",
}
local treedefs =
{
	
}
local schem_count = #schematics
local l_system_count = #treedefs

minetest.register_node(modname .. ":sapling",
	{
		description = S("Sapling"),
		drawtype = "mesh",
		mesh = modname .. "_sapling.obj",
		tiles = {modname .. "_leaves.png", modname .. "_wood_sides.png"},
		groups = {dig_immediate = 2, attached_node = 1},
		paramtype = "light",
		walkable = false,
		is_ground_content = false,
		selection_box =
		{
			type = "fixed",
			fixed =
			{
				{-0.125, -0.5, -0.125, 0.125, 0.125, 0.125}
			}
		},
		on_construct = function(pos)
			local timer = get_node_timer(pos)
			timer:start(random(120, 1200)) --TODO: make settings
		end,
		on_timer = function(pos, elapsed)			
			--delete sapling
			remove_node(pos)
			
			local index = random(schem_count + l_system_count)
			if index > schem_count
			then
				--place l-system
				spawn_tree(pos, treedefs[index - schem_count])
			else
				--place schematic
				local schem = schematics[index]
				place_schematic(pos, schem, "random", nil, false, "place_center_x, place_center_z")
			end
		end
	})
