ISRenameEverything = ISRenameEverything or {};

local _ISInventoryPage_createChildren = ISInventoryPage.createChildren
local _ISInventoryPage_prerender = ISInventoryPage.prerender

local disallowedTypes = {
    ["floor"] = true,
    ["TruckBed"] = true,
    ["SeatFrontLeft"] = true,
    ["SeatFrontRight"] = true,
    ["SeatRearLeft"] = true,
    ["SeatRearRight"] = true,
    ["GloveBox"] = true,
}

local function findTitleWidth(instance)
    local text = ""
    if not instance then return 0 end
    if not instance.inventoryPane then return 0 end

    if instance.title and not instance.onCharacter then
        text = instance.title
        if instance.inventoryPane.inventory and instance.inventoryPane.inventory:getParent() then
            local fireTile = instance.inventoryPane.inventory:getParent()
            local campfire = CCampfireSystem.instance:getLuaObjectOnSquare(fireTile:getSquare())
            if campfire then
                text = text ..
                    ": " ..
                    (ISCampingMenu.timeString(luautils.round(campfire.fuelAmt))) -- .. " (" .. fireState .. ")"
            elseif fireTile and fireTile:isFireInteractionObject() then
                if fireTile:isPropaneBBQ() and not fireTile:hasPropaneTank() then
                    text = text .. ": " .. getText("IGUI_BBQ_NeedsPropaneTank")
                else
                    text = text ..
                        ": " ..
                        tostring(ISCampingMenu.timeString(fireTile:getFuelAmount())) -- .. " (" .. fireState .. ")"
                end
            end
        end
        -- used handle characters being in seats
        if instance.inventoryPane.inventory and instance.inventoryPane.inventory:isOccupiedVehicleSeat() then
            text = text .. " " .. getText("IGUI_invpage_Occupied")
        end
    end

    return getTextManager():MeasureStringX(UIFont.Small, text)
end

function ISInventoryPage:createChildren()
    _ISInventoryPage_createChildren(self)

    -- Create a button to rename the container
    local weightWid = math.max(90, getTextManager():MeasureStringX(UIFont.Small, "99.99 / 99") + 10)
    self.titleButton = ISButton:new(self.width - 20 - weightWid, 0, 0, self:titleBarHeight(), "", self,
        ISInventoryPage.OnRenameContainer)
    self.titleButton:initialise()
    self.titleButton.borderColor.a = 0.0
    self.titleButton.backgroundColor.a = 0.0
    self.titleButton.backgroundColorMouseOver.a = 0.7
    self.titleButton:setTooltip(getText("ContextMenu_renameButton"))
    self:addChild(self.titleButton)
    self.titleButton:setVisible(false)
end

function ISInventoryPage:prerender()
    -- check if the inventory has a parent and modData for custom name exists
    if self.title and not self.onCharacter and not disallowedTypes[self.inventory:getType()] and self.inventory:getParent() then
        local modData = self.inventory:getParent():getModData()
        if modData.renameEverything_name and modData.renameEverything_name ~= "" then
            -- if custom name exists, use it as the new title
            self.title = modData.renameEverything_name
        end
    end

    -- call the original prerender function
    _ISInventoryPage_prerender(self)

    -- check if the conditions for a custom title are still met
    if self.title and not self.onCharacter and not disallowedTypes[self.inventory:getType()] and self.inventory:getParent() then
        local weightWid = getTextManager():MeasureStringX(UIFont.Small, "99.99 / 99")
        weightWid = math.max(90, weightWid + 10)

        local fullTextWidth = findTitleWidth(self)
        local titleWidth = getTextManager():MeasureStringX(UIFont.Small, self.title)
        local x = self.width - 35 - weightWid - fullTextWidth

        self:drawTextureScaled(self.titlebarbkg, x, 1, titleWidth, self:titleBarHeight() - 2, 1, 1, 1, 1);

        -- update button
        self.titleButton:setVisible(true)
        self.titleButton:setX(x)
        self.titleButton:setTitle(self.title)
        self.titleButton:setWidthToTitle()
        self.titleButton:setWidth(self.titleButton:getWidth() - 8)
    else
        -- if custom title not applicable, hide the button
        self.titleButton:setVisible(false)
    end
end

function ISInventoryPage:OnRenameContainer()
    -- create a modal dialog box with a text input field
    local modal = ISTextBox:new(0, 0, 280, 180, getText("ContextMenu_label_containers"), self.title, nil,
        ISInventoryPage.onRenameContainerClick, self.player, self.inventory)
    modal:initialise()
    modal:addToUIManager()

    -- set the focus to the text input field so the player can start typing right away
    modal.entry:focus()
end

function ISInventoryPage:onRenameContainerClick(button, inventory)
    if button.internal == "OK" then
        -- Check if the textbox input is not empty
        if button.parent.entry:getText() and button.parent.entry:getText() ~= "" then
            -- Set the custom name for the container in the parent's mod data to the input text
            inventory:getParent():getModData().renameEverything_name = button.parent.entry:getText()
            -- Transmit the mod data to synchronize it for multiplayer
            inventory:getParent():transmitModData()
        end
    end
end
