-- Helpful reference when working with cairo:
-- * https://github.com/pavouk/lgi/blob/master/samples/cairo.lua
-- * https://www.cairographics.org/manual/cairo-cairo-t.html
-- * https://www.cairographics.org/operators/
-- * https://www.cairographics.org/manual/cairo-cairo-t.html#cairo-operator-t

local utils = {}

local lgi = require("lgi")
local cairo = lgi.cairo

function utils.bindings(keybindings_tree)
	local keybindings = {}
	local trees = {keybindings_tree}
	while #trees > 0 do
		local tree = table.remove(trees)
		for _, subtree in ipairs(tree) do
			if type(subtree) == "table" and not subtree.binding then
				table.insert(trees, subtree)
			else
				subtree.binding = nil
				table.insert(keybindings, subtree)
			end
		end
	end
	return keybindings
end

function utils.group(group_name, keybindings)
	for _, key in ipairs(keybindings) do
		key.group = group_name
	end
	return keybindings
end

function utils.keybind(modifiers, key, on_press)
	local keybind_keys = awful.key{
		modifiers = modifiers,
		key = key,
		on_press = on_press,
	}
	keybind_keys.binding = true
	return keybind_keys
end

function utils.keybind_grp(modifiers, keygroup, on_press)
	local keys_grp = awful.key{
		modifiers = modifiers,
		keygroup = keygroup,
		on_press = on_press,
	}
	keys_grp.binding = true
	return keys_grp
end

function utils.buttonbind(modifiers, key, on_press)
	local btns = awful.button(modifiers, key, on_press)
	btns.binding = true
	return btns
end

function utils.wrap_spawn(process)
	return function()
		awful.spawn(process)
	end
end

function utils.wrap_spawn_with_shell(process)
	return function()
		awful.spawn(process)
	end
end

function utils.clone_image(img)
	local cloned = cairo.ImageSurface.create(cairo.Format.ARGB32, img.width, img.height)
	local cr = cairo.Context(cloned)
	cr:set_source_surface(img, 0, 0)
	cr:paint()
	return cloned
end

function utils.overwrite_colored_image(img, on_top_image, color)
	local cr = cairo.Context(img)
	cr:set_operator(2) -- CAIRO_OPERATOR_OVER = 2
	cr:set_source_surface(on_top_image, 0, 0)
	cr:paint()
	cr:set_source(gears.color(color))
	cr:set_operator(5) -- CAIRO_OPERATOR_ATOP = 5
	cr:paint()
end

return utils
