-- Place this script nearby with the gui component to able make requests
-- To the go namespace from GUI with events systems (cross context)
-- This one is a required to make a unified "Shaders" pipeline in the GUI scripts
-- This required to grab a texture data with `go.get` function

local queues = require("event.queues")

---Usage: queues.push("druid.get_atlas_path", {
---	texture_name = gui.get_texture(self.node),
---	sender = msg.url(),
---}, callback, [context])
---Pass texture name to get atlas info and sender url to check if the request is valid
local MESSAGE_GET_ATLAS_PATH = "druid.get_atlas_path"

---@class druid.get_atlas_path_request
---@field texture_name hash
---@field sender hash

---@param request druid.get_atlas_path_request
---@return string?
local function get_atlas_path(self, request)
	local my_url = msg.url()
	my_url.fragment = nil

	local copy_url = msg.url(request.sender)
	copy_url.fragment = nil

	-- This check should works well
	if my_url ~= copy_url then
		return nil
	end

	return go.get(request.sender, "textures", { key = request.texture_name })
end


function init(self)
	queues.subscribe(MESSAGE_GET_ATLAS_PATH, get_atlas_path, self)
end


function final(self)
	queues.unsubscribe(MESSAGE_GET_ATLAS_PATH, get_atlas_path, self)
end
