if isServer() then return end

-- Add context action
local function contextFunc(player, context, worldobjects, test)
	CTags:contextFunction(player, context, worldobjects, test)
end
Events.OnFillWorldObjectContextMenu.Add(contextFunc);

-- Tag tracker
function CTags:tagTracker()
	local tagData = ModData.getOrCreate("ContainerTagData");
	if not tagData.tags then tagData.tags = {} end;
	local data = tagData.tags;
	local player = getPlayer();

	-- Clear drawData
	CTags.drawData = {}; 

	-- Read data and populate list 
	for i, tag in pairs(data) do 
		local squareCoords = tag.square;
		if squareCoords then
			if player:getZ() == squareCoords[3] then 
				local square = getCell():getGridSquare(squareCoords[1], squareCoords[2], squareCoords[3]);
				if square then 
					local objects = square:getObjects();
					local isPresent = false;
					for j=0, objects:size()-1 do
						local object = objects:get(j);
						local container = object:getContainer();
						if container then
							table.insert(CTags.drawData, { ['square'] = square, ['coords'] = squareCoords, ['text'] = tag.tag, ['color'] = tag.color });
							isPresent = CTags:inSafehouse(object);
							break
						end
					end

					-- Not anymore, cleanup
					if not isPresent then
						local squareID = "" .. squareCoords[1] .. "." .. squareCoords[2] .. "." .. squareCoords[3]; 
						tagData.tags[squareID] = {};
					end 
				end				
			end			
		end
	end

	-- Run overlay
	if getPlayer() and not CTagsOverlay.window then
		CTagsOverlay:make()
	end 

	CTags:sleepDo(0.25, CTags.tagTracker); 	
end


-- Runtime

local function OnInitGlobalModData(isNewGame)
	CTags:sleepDo(0, CTags.tagTracker);
end	
Events.OnInitGlobalModData.Add(OnInitGlobalModData)
