local druid = require("druid.druid")


local function add_element(self)
	-- Limit up to 10 nodes in this example
	if #self.grid.nodes >= 10 then
		return
	end

	-- Make new element to insert into the grid
	local nodes = gui.clone_tree(self.prefab)
	gui.set_enabled(nodes["prefab"], true)
	self.grid:add(nodes["prefab"])
	gui.set_text(nodes["prefab_text"], #self.grid.nodes)

	-- Animate new element after _grid:add_
	-- Note, what Grid component take care of node position, so we can't
	-- animate position of the root node. We need insert one more anchor node to make
	-- it possible. In this example it is "prefab_icon"
	gui.animate(nodes["prefab_icon"], "position.y", 20, gui.EASING_OUTSINE, 0.4, 0, nil, gui.PLAYBACK_ONCE_BACKWARD)
	gui.animate(nodes["prefab_icon"], "color.w", 0, gui.EASING_OUTSINE, 0.3, 0, nil, gui.PLAYBACK_ONCE_BACKWARD)
end


local function remove_element(self)
	if #self.grid.nodes > 0 then
		local root = self.grid:remove(#self.grid.nodes)
		-- We should instant remove element from the grid, but node itself delete after the animation
		gui.animate(root, "color.w", 0, gui.EASING_OUTSINE, 0.2, 0, function()
			gui.delete_node(root)
		end)
	end
end


function init(self)
	self.druid = druid.new(self)
	self.grid = self.druid:new_static_grid("grid", "prefab", 5)

	self.prefab = gui.get_node("prefab")
	gui.set_enabled(self.prefab, false)

	self.druid:new_button("button_add/button", add_element)
	self.druid:new_button("button_remove/button", remove_element)
end


function final(self)
	self.druid:final()
end


function update(self, dt)
	self.druid:update(dt)
end


function on_message(self, message_id, message, sender)
	self.druid:on_message(message_id, message, sender)
end


function on_input(self, action_id, action)
	return self.druid:on_input(action_id, action)
end
