-- W900 Freezer Radial Menu Integration
-- Client-side radial menu extension for toggling freezer on/off

require "Vehicles/ISUI/ISVehicleMenu"

local W900FreezerMenu = {}

-- Store original function
if not W900FreezerMenu.oldShowRadialMenu then
    W900FreezerMenu.oldShowRadialMenu = ISVehicleMenu.showRadialMenu
end

-- Override radial menu to add our freezer option
function ISVehicleMenu.showRadialMenu(playerObj)
    -- Call original function first
    W900FreezerMenu.oldShowRadialMenu(playerObj)
    
    -- Add our W900 freezer option
    W900FreezerMenu.showRadialMenu(playerObj)
end

function W900FreezerMenu.showRadialMenu(playerObj)
    local vehicle = playerObj:getVehicle()
    if not vehicle then return end
    
    -- Only show if player is in vehicle
    if vehicle:isDriver(playerObj) then
        -- Check if vehicle has TruckBed and Freezersystem parts
        local truckBed = vehicle:getPartById("TruckBed")
        local freezerSystem = vehicle:getPartById("Freezersystem")
        
        if truckBed and freezerSystem and freezerSystem:getInventoryItem() then
            local menu = getPlayerRadialMenu(playerObj:getPlayerNum())
            
            -- Check if freezer is active - read from ModData
            local modData = truckBed:getModData()
            local isActive = modData.tsarslib and modData.tsarslib.active or false
            
            --print(("W900 Client: TruckBed ModData check - active: " .. tostring(isActive))
            
            if isActive then
                menu:addSlice(
                    getText("IGUI_Turn_Freezer_Off"), 
                    getTexture("media/ui/Container_Freezer"), 
                    W900FreezerMenu.onToggleFreezer, 
                    playerObj, vehicle, truckBed
                )
            else
                menu:addSlice(
                    getText("IGUI_Turn_Freezer_On"), 
                    getTexture("media/ui/Container_Freezer"), 
                    W900FreezerMenu.onToggleFreezer, 
                    playerObj, vehicle, truckBed
                )
            end
        end
    end
end

-- Toggle freezer on/off
function W900FreezerMenu.onToggleFreezer(playerObj, vehicle, part)
    -- Important: In multiplayer, we need to request current state from server
    -- For now, we'll read local ModData but server will be source of truth
    local modData = part:getModData()
    
    -- Initialize if needed
    if not modData.tsarslib then
        modData.tsarslib = {}
    end
    
    local currentState = modData.tsarslib.active or false
    local newState = not currentState
    
    --print(("W900 Client: Toggle freezer - current: " .. tostring(currentState) .. " -> new: " .. tostring(newState))
    
    -- Optimistically update local state for immediate feedback
    modData.tsarslib.active = newState
    
    -- Send command to server for authoritative update
    local args = {
        vehicle = vehicle:getId(),
        part = part:getId(),
        active = newState
    }
    
    sendClientCommand(playerObj, 'W900', 'toggleFreezer', args)
end

local function refreshPageForContainer(page, container)
    if not page or not page.inventoryPane or not container then
        return
    end

    local selectedInventory = page.inventoryPane.inventory
    if not selectedInventory then
        return
    end

    if selectedInventory ~= container then
        local selectedParent = selectedInventory.getParent and selectedInventory:getParent() or nil
        local targetParent = container.getParent and container:getParent() or nil
        if not selectedParent or not targetParent then
            return
        end
        local selectedVehicleId = selectedParent.getId and selectedParent:getId() or nil
        local targetVehicleId = targetParent.getId and targetParent:getId() or nil
        if selectedVehicleId and targetVehicleId then
            if selectedVehicleId ~= targetVehicleId then
                return
            end
        elseif selectedParent ~= targetParent then
            return
        end
    end

    if selectedInventory.requestServerItemsForContainer then
        selectedInventory:requestServerItemsForContainer()
    end

    if selectedInventory.requestSync then
        selectedInventory:requestSync()
    end

    if selectedInventory.setDrawDirty then
        selectedInventory:setDrawDirty(true)
    end

    page:refreshBackpacks()
    page.inventoryPane:refreshContainer()
end

function W900FreezerMenu.onServerCommand(module, command, args)
    if module ~= 'W900' or command ~= 'refreshFreezerContainer' or not args then
        return
    end

    local vehicle = getVehicleById and getVehicleById(args.vehicle)
    if not vehicle then
        return
    end

    local part = vehicle:getPartById(args.part)
    if not part or not part:getItemContainer() then
        return
    end

    local container = part:getItemContainer()
    local activePlayers = getNumActivePlayers and getNumActivePlayers() or 1
    for playerNum = 0, activePlayers - 1 do
        refreshPageForContainer(getPlayerLoot and getPlayerLoot(playerNum) or nil, container)
        refreshPageForContainer(getPlayerInventory and getPlayerInventory(playerNum) or nil, container)
    end
end

if not W900FreezerMenu.serverCommandInstalled then
    Events.OnServerCommand.Add(W900FreezerMenu.onServerCommand)
    W900FreezerMenu.serverCommandInstalled = true
end

--print(("W900: Freezer radial menu loaded")
