local addonName, addon = ...

--[[-----------------------------------------------------------------------------
Relocate the Backpack and Bags
-------------------------------------------------------------------------------]]


local function GUIUpdateContainerFrameAnchors()

		local frame, xOffset, yOffset, screenHeight, freeScreenHeight, leftMostPoint, column;
		local screenWidth = GetScreenWidth()
		local bagScale = 0.85;
		local leftLimit = 0;

		if ( BankFrame:IsShown() ) then
			leftLimit = BankFrame:GetRight() - 25;
		end

		if (bagScale == 0.85) then

			while ( bagScale > CONTAINER_SCALE ) do
				screenHeight = GetScreenHeight() / bagScale;
				-- Adjust the start anchor for bags depending on the multibars
				xOffset = CONTAINER_OFFSET_X / bagScale;
				yOffset = CONTAINER_OFFSET_Y / bagScale;
				-- freeScreenHeight determines when to start a new column of bags
				freeScreenHeight = screenHeight - yOffset;
				leftMostPoint = screenWidth - xOffset;
				column = 1;
				local frameHeight;
				for index, frameName in ipairs(ContainerFrame1.bags) do
					frameHeight = _G[frameName]:GetHeight()
					if ( freeScreenHeight < frameHeight ) then
						-- Start a new column
						column = column + 1;
						leftMostPoint = screenWidth - ( column * CONTAINER_WIDTH * bagScale ) - xOffset;
						freeScreenHeight = screenHeight - yOffset;
					end
					freeScreenHeight = freeScreenHeight - frameHeight - VISIBLE_CONTAINER_SPACING;
				end
				if ( leftMostPoint < leftLimit ) then
					bagScale = bagScale - 0.01;
				else
					break;
				end
			end

			if ( bagScale < CONTAINER_SCALE ) then
				bagScale = CONTAINER_SCALE;
			end
		else
			bagScale = 0.85
		end

		screenHeight = GetScreenHeight() / bagScale;
		xOffset = 45 / bagScale;
		yOffset = 330 / bagScale;
		freeScreenHeight = screenHeight - yOffset;
		column = 0;

		for index, frameName in ipairs(ContainerFrame1.bags) do
			frame = _G[frameName]
			frame:SetScale(bagScale)
			frame:ClearAllPoints()
			if ( index == 1 ) then
				-- First bag
				frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -xOffset, yOffset )
			elseif ( freeScreenHeight < frame:GetHeight() ) then
				-- Start a new column
				column = column + 1;
				freeScreenHeight = screenHeight - yOffset;
				frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -(column * CONTAINER_WIDTH) - xOffset, yOffset )
			else
				-- Anchor to the previous bag
				frame:SetPoint("BOTTOMRIGHT", ContainerFrame1.bags[index - 1], "TOPRIGHT", 0, CONTAINER_SPACING)
			end
			freeScreenHeight = freeScreenHeight - frame:GetHeight() - VISIBLE_CONTAINER_SPACING;
		end

end

hooksecurefunc("updateContainerFrameAnchors", GUIUpdateContainerFrameAnchors)
