require "ISUI/ISInventoryPage"

function ISInventoryPage:refreshBackpacks()
	for i,v in ipairs(self.backpacks) do
		self:removeChild(v);
	end

	if ISInventoryPage.floorContainer == nil then
		ISInventoryPage.floorContainer = {}
	end
	if ISInventoryPage.floorContainer[self.player+1] == nil then
		ISInventoryPage.floorContainer[self.player+1] = ItemContainer.new("floor", nil, nil, 10, 10);
		ISInventoryPage.floorContainer[self.player+1]:setExplored(true)
	end

	self.inventoryPane.lastinventory = self.inventoryPane.inventory;

	self.inventoryPane:hideButtons()

    local oldNumBackpacks = #self.backpacks
	self.backpacks = {}

    local found = false;
	local c = 1;
    local foundIndex = -1;
	local containerButton = nil;

    local playerObj = getSpecificPlayer(self.player)

    if self.onCharacter then
        containerButton = ISButton:new(self:getWidth()-32, ((c-1)*32)+15, 32, 32, "", self, ISInventoryPage.selectContainer, ISInventoryPage.onBackpackMouseDown, true);
        containerButton.anchorBottom = false;
        containerButton.anchorRight = true;
        containerButton.anchorTop = false;
        containerButton.anchorLeft = false;
        containerButton.name = getText("IGUI_InventoryName", getSpecificPlayer(self.player):getDescriptor():getForename(), getSpecificPlayer(self.player):getDescriptor():getSurname());
        if not self.title then
            self.title = containerButton.name;
        end
        containerButton:setOnMouseOverFunction(ISInventoryPage.onMouseOverButton);
        containerButton:setOnMouseOutFunction(ISInventoryPage.onMouseOutButton);
        containerButton:initialise();
        containerButton.borderColor.a = 0.0;
        containerButton.capacity = self.inventory:getMaxWeight();
        if not self.capacity then
            self.capacity = containerButton.capacity;
        end
        containerButton.backgroundColor.a = 0.0;
        containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
        containerButton:setImage(self.invbasic);

        containerButton.inventory = getSpecificPlayer(self.player):getInventory();

        if self.inventoryPane.inventory == containerButton.inventory then
            containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0};
            foundIndex = c
            found = true;
        end
        self:addChild(containerButton);
        self.backpacks[c] = containerButton;
        c = c + 1;
        local it = getSpecificPlayer(self.player):getInventory():getItems();
        for i = 0, it:size()-1 do
            local item = it:get(i);

            if item:getCategory() == "Container" and getSpecificPlayer(self.player):isEquipped(item) or item:getType() == "KeyRing" 
			or item:getType() == "Pouch" or item:getType() == "Holster" or item:getType() == "KnifeCase" or item:getType() == "FirstAidKit" 
			or item:getType() == "TacticalCase" or item:getType() == "ExtraBag" or item:getType() == "TacticalBelt" or item:getType() == "BananaBag"
			or item:getType() == "TacticalBeltHol" or item:getType() == "TacticalBeltKni" or item:getType() == "TacticalBeltHolKni" 
			or item:getType() == "TacticalBeltKniKni" or item:getType() == "TacticalBeltHolHol" then
                -- found a container, so create a button for it...
                local containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, ISInventoryPage.selectContainer, ISInventoryPage.onBackpackMouseDown, true);
                containerButton:setImage(item:getTex());
                containerButton:forceImageSize(30, 30)
                containerButton.anchorBottom = false;
                containerButton:setOnMouseOverFunction(ISInventoryPage.onMouseOverButton);
                containerButton:setOnMouseOutFunction(ISInventoryPage.onMouseOutButton);
                containerButton.anchorRight = true;
                containerButton.anchorTop = false;
                containerButton.anchorLeft = false;
                containerButton:initialise();
                containerButton.borderColor.a = 0.0;
                containerButton.backgroundColor.a = 0.0;
                containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
                containerButton.inventory = item:getInventory();
                containerButton.capacity = item:getEffectiveCapacity(playerObj);
                containerButton.name = item:getName();
                if self.inventoryPane.inventory == containerButton.inventory then
                    containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0};
                    foundIndex = c;
                    found = true;
                end
                self:addChild(containerButton);
                self.backpacks[c] = containerButton;
                c = c + 1;
            end

        end
    else
  --  print("a");
        local cx = getSpecificPlayer(self.player):getX();
        local cy = getSpecificPlayer(self.player):getY();
        local cz = getSpecificPlayer(self.player):getZ();
  --  print("b");
      -- Do floor
        --

        --
        local container = ISInventoryPage.floorContainer[self.player+1]
        getCell():getProcessItems():removeAll(container:getItems())
        ISInventoryPage.floorContainer[self.player+1]:clear();

        local sqs = {}

        local dir = getSpecificPlayer(self.player):getDir();

        if(dir == IsoDirections.N) then         sqs[2] = getCell():getGridSquare(cx-1, cy-1, cz); sqs[3] = getCell():getGridSquare(cx, cy-1, cz); sqs[4] = getCell():getGridSquare(cx+1, cy-1, cz);
        elseif (dir == IsoDirections.NE) then   sqs[2] = getCell():getGridSquare(cx, cy-1, cz); sqs[3] = getCell():getGridSquare(cx+1, cy-1, cz); sqs[4] = getCell():getGridSquare(cx+1, cy, cz);
        elseif (dir == IsoDirections.E) then    sqs[2] = getCell():getGridSquare(cx+1, cy-1, cz); sqs[3] = getCell():getGridSquare(cx+1, cy, cz); sqs[4] = getCell():getGridSquare(cx+1, cy+1, cz);
        elseif (dir == IsoDirections.SE) then   sqs[2] = getCell():getGridSquare(cx+1, cy, cz); sqs[3] = getCell():getGridSquare(cx+1, cy+1, cz); sqs[4] = getCell():getGridSquare(cx, cy+1, cz);
        elseif (dir == IsoDirections.S) then    sqs[2] = getCell():getGridSquare(cx+1, cy+1, cz); sqs[3] = getCell():getGridSquare(cx, cy+1, cz); sqs[4] = getCell():getGridSquare(cx-1, cy+1, cz);
        elseif (dir == IsoDirections.SW) then   sqs[2] = getCell():getGridSquare(cx, cy+1, cz); sqs[3] = getCell():getGridSquare(cx-1, cy+1, cz); sqs[4] = getCell():getGridSquare(cx-1, cy, cz);
        elseif (dir == IsoDirections.W) then    sqs[2] = getCell():getGridSquare(cx-1, cy+1, cz); sqs[3] = getCell():getGridSquare(cx-1, cy, cz); sqs[4] = getCell():getGridSquare(cx-1, cy-1, cz);
        elseif (dir == IsoDirections.NW) then   sqs[2] = getCell():getGridSquare(cx-1, cy, cz); sqs[3] = getCell():getGridSquare(cx-1, cy-1, cz); sqs[4] = getCell():getGridSquare(cx, cy-1, cz);
        end

        sqs[1] = getCell():getGridSquare(cx, cy, cz);
   -- print("c");
        for x = 1, 4 do
            local gs = sqs[x];

            -- stop grabbing thru walls...
            local currentSq = getSpecificPlayer(self.player):getCurrentSquare()
            if gs ~= currentSq and currentSq and currentSq:isBlockedTo(gs) then
                gs = nil
            end

            -- don't show containers in safehouse if you're not allowed
            if gs and isClient() and SafeHouse.isSafeHouse(gs, getSpecificPlayer(self.player):getUsername()) and not ServerOptions.getBoolean("SafehouseAllowLoot") then
                gs = nil;
            end

            if gs ~= nil then

            --for y = -1, 1 do
                local obs = gs:getObjects();
                local sobs =  gs:getStaticMovingObjects();
                local wobs = gs:getWorldObjects();

                if wobs ~= nil then
                    for i = 0, wobs:size()-1 do
                        local o = wobs:get(i);
                        if instanceof(o, "IsoWorldInventoryObject") then
                            -- FIXME: An item can be in only one container; in coop the item won't be displayed for every player.
	                        ISInventoryPage.floorContainer[self.player+1]:AddItem(o:getItem());
                        end
                    end
                end

                for i = 0, sobs:size()-1 do
                    local so = sobs:get(i);
                    local doIt = true;

                    if so:getContainer() ~= nil then
                        -- if container is locked with a padlock and we don't have the key, return

                        if instanceof(so, "IsoThumpable") and so:isLockedByPadlock() and not getSpecificPlayer(self.player):getInventory():haveThisKey(so:getKeyId()) then
                            doIt = false;
                        end
                        if doIt then
                            local containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, ISInventoryPage.selectContainer, ISInventoryPage.onBackpackMouseDown, true);
                            containerButton.anchorBottom = false;
                            containerButton:setOnMouseOverFunction(ISInventoryPage.onMouseOverButton);
                            containerButton:setOnMouseOutFunction(ISInventoryPage.onMouseOutButton);
                            containerButton.anchorRight = true;
                            containerButton.anchorTop = false;
                            containerButton.anchorLeft = false;
                            containerButton:initialise();
                            containerButton.borderColor.a = 0.0;
                            containerButton.backgroundColor.a = 0.0;
                            containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
                            containerButton.inventory = so:getContainer();
                            containerButton.capacity = so:getContainer():getEffectiveCapacity(playerObj);
                            if self.containerIconMaps[containerButton.inventory:getType()] ~= nil then
                                containerButton:setImage(self.containerIconMaps[containerButton.inventory:getType()]);
                            else
                                containerButton:setImage(self.conDefault);
                            end
                            containerButton:forceImageSize(30, 30)
                            containerButton.name = "";--getSpecificPlayer(self.player):getDescriptor():getForename().." "..getSpecificPlayer(self.player):getDescriptor():getSurname().."'s " .. item:getName();
                            if self.inventoryPane.inventory == containerButton.inventory then
                                containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0};
                                foundIndex = c;
                                found = true;
                            end
                            if not containerButton.inventory:isExplored() then
                                if not isClient() then
                                    ItemPicker.fillContainer(containerButton.inventory, self.player)
                               else
                                   containerButton.inventory:requestServerItemsForContainer();
                               end
                                containerButton.inventory:setExplored(true);
                            end
                            self:addChild(containerButton);
                            self.backpacks[c] = containerButton;
                            c = c + 1;
                        end
                    end
                end

                for i = 0, obs:size()-1 do
                   local o = obs:get(i);
                    local doIt = true;

                   if o:getContainer() ~= nil then
                       if doIt then
                           -- if container is locked with a padlock and we don't have the key, don't allow it to open
--                           if instanceof(o, "IsoThumpable") and ((o:isLockedByPadlock() and not getSpecificPlayer(self.player):getInventory():haveThisKeyId(o:getKeyId())) or o:getLockedByCode() > 0) then
----                               local containerImage = ISImage:new(self.width-32, ((c-1)*32)+15, 32, 32, getTexture("media/ui/Container_Crate.png"));
----                               if self.containerIconMaps[o:getContainer():getType()] ~= nil then
----                                   containerImage.texture = self.containerIconMaps[o:getContainer():getType()];
----                               end
----                               containerImage.textureOverride = getTexture("media/ui/lock.png");
----                               self:addChild(containerImage);
----                               c = c + 1;
--
--                               local containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, nil, nil, true);
--                               containerButton.anchorBottom = false;
--                               containerButton.anchorRight = true;
--                               containerButton.anchorTop = false;
--                               containerButton.anchorLeft = false;
--                               containerButton:initialise();
--                               containerButton.borderColor.a = 0.0;
--                               containerButton.backgroundColor.a = 0.0;
--                               containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
--
--                               if self.containerIconMaps[o:getContainer():getType()] ~= nil then
--                                   containerButton:setImage(self.containerIconMaps[o:getContainer():getType()]);
--                               else
--                                   containerButton:setImage(self.conDefault);
--                               end
--                               containerButton:forceImageSize(30, 30)
--
--                               containerButton.textureOverride = getTexture("media/ui/lock.png");
--
--                               self:addChild(containerButton);
--                               self.backpacks[c] = containerButton;
-- else
                           local containerButton = nil;
                           if instanceof(o, "IsoThumpable") and o:isLockedToCharacter(playerObj) then
                               containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, nil,nil, true);
                               containerButton.textureOverride = getTexture("media/ui/lock.png");
                           else
                               containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, ISInventoryPage.selectContainer, ISInventoryPage.onBackpackMouseDown, true);
                               containerButton:setOnMouseOverFunction(ISInventoryPage.onMouseOverButton);
                               containerButton:setOnMouseOutFunction(ISInventoryPage.onMouseOutButton);
                           end
                           containerButton.anchorBottom = false;
                           containerButton.anchorRight = true;
                           containerButton.anchorTop = false;
                           containerButton.anchorLeft = false;
                           containerButton:initialise();
                           containerButton.borderColor.a = 0.0;
                           containerButton.backgroundColor.a = 0.0;
                           containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
                           containerButton.inventory = o:getContainer();

                           if instanceof(o, "IsoThumpable") and o:isLockedByPadlock() and getSpecificPlayer(self.player):getInventory():haveThisKeyId(o:getKeyId()) then
                               containerButton.textureOverride = getTexture("media/ui/lockOpen.png");
                           end

                           containerButton.capacity = o:getContainer():getEffectiveCapacity(playerObj);
                           if self.containerIconMaps[containerButton.inventory:getType()] ~= nil then
                                containerButton:setImage(self.containerIconMaps[containerButton.inventory:getType()]);
                           else
                               containerButton:setImage(self.conDefault);
                           end
                           containerButton:forceImageSize(30, 30)
                           containerButton.name = "";--getSpecificPlayer(self.player):getDescriptor():getForename().." "..getSpecificPlayer(self.player):getDescriptor():getSurname().."'s " .. item:getName();
                           if self.inventoryPane.inventory == containerButton.inventory then
                               containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0};
                               foundIndex = c;
                               found = true;
                           end
                           if not containerButton.inventory:isExplored() then

                               if not isClient() then
                                   ItemPicker.fillContainer(containerButton.inventory, self.player);
                               else
                                   containerButton.inventory:requestServerItemsForContainer();
                               end

                               containerButton.inventory:setExplored(true);
                           end
                           self:addChild(containerButton);
                           self.backpacks[c] = containerButton;
                           c = c + 1;
                       end
                   end


                end
            end

        end
   -- print("d");
        local containerButton = ISButton:new(self.width-32, ((c-1)*32)+15, 32, 32, "", self, ISInventoryPage.selectContainer, ISInventoryPage.onBackpackMouseDown, true);
        containerButton:setImage(self.conFloor);
        containerButton:forceImageSize(30, 30)
        containerButton.anchorBottom = false;
        containerButton:setOnMouseOverFunction(ISInventoryPage.onMouseOverButton);
        containerButton:setOnMouseOutFunction(ISInventoryPage.onMouseOutButton);
        containerButton.anchorRight = true;
        containerButton.anchorTop = false;
        containerButton.anchorLeft = false;
        containerButton:initialise();
        containerButton.borderColor.a = 0.0;
        containerButton.backgroundColor.a = 0.0;
        containerButton.backgroundColorMouseOver = {r=0.3, g=0.3, b=0.3, a=1.0};
        containerButton.inventory = ISInventoryPage.floorContainer[self.player+1];
        containerButton.capacity = ISInventoryPage.floorContainer[self.player+1]:getMaxWeight();
        containerButton.name = "";--getSpecificPlayer(self.player):getDescriptor():getForename().." "..getSpecificPlayer(self.player):getDescriptor():getSurname().."'s " .. item:getName();
        if self.inventoryPane.inventory == containerButton.inventory then
	        containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0};
	        foundIndex = c;
	        found = true;
        end
        self:addChild(containerButton);
        self.backpacks[c] = containerButton;
        local floor = c;
        c = c + 1;
   -- print("e");
        if not containerButton.inventory:isExplored() then
            if not isClient() then
				ItemPicker.fillContainer(containerButton.inventory, self.player);
            else
                containerButton.inventory:requestServerItemsForContainer();
            end
	        containerButton.inventory:setExplored(true);
        end

    end
--	print("f");
	self.inventoryPane.inventory = self.inventoryPane.lastinventory;
	self.inventory = self.inventoryPane.inventory;
    if self.backpackChoice ~= nil and getSpecificPlayer(self.player):getJoypadBind() ~= -1 then
        if self.backpackChoice >= c then
	        if #self.backpacks > 1 then
		        self.backpackChoice = 2;
	        else
		        self.backpackChoice = 1;
	        end

        end
        if self.backpacks[self.backpackChoice] ~= nil then
            self.inventoryPane.inventory = self.backpacks[self.backpackChoice].inventory;
        end
    else
--	    print("g");
        if not self.onCharacter and oldNumBackpacks == 1 and c > 1 then
            self.inventoryPane.inventory = self.backpacks[1].inventory;
            self.capacity = self.backpacks[1].capacity
	    elseif found then
            self.capacity = self.backpacks[foundIndex].capacity
	    elseif not found and c > 1 then
            if self.backpacks[1] and self.backpacks[1].inventory then
                self.inventoryPane.inventory = self.backpacks[1].inventory;
                self.capacity = self.backpacks[1].capacity
            end
        elseif self.inventoryPane.lastinventory ~= nil then
            self.inventoryPane.inventory = self.inventoryPane.lastinventory;
        end

--	    print("h");
    end

    if not found then
        self.toggleStove:setVisible(false);
    end
	self.inventoryPane:bringToTop();

    self.resizeWidget2:bringToTop();
    self.resizeWidget:bringToTop();
--	print("i");

    self.inventory = self.inventoryPane.inventory;
--	print("j");

    for k,containerButton in ipairs(self.backpacks) do
        if containerButton.inventory == self.inventory then
            containerButton.backgroundColor = {r=0.7, g=0.7, b=0.7, a=1.0}
        else
            containerButton.backgroundColor.a = 0
        end
    end

    if self.inventoryPane ~= nil then self.inventoryPane:refreshContainer(); end
	self:refreshWeight();

	self:syncToggleStove()
end