-- W900 Cistern Trailer Refueling at Gas Stations
-- Client-side refueling integration for cistern trailers

require "Vehicles/TimedActions/ISRefuelFromGasPump"
require "Vehicles/ISUI/ISVehiclePartMenu"
require "W900_CisternParts"
local W900CisternContext = require "W900_CisternContext"

local W900CisternRefuel = {}

local function isPoweredFuelPump(obj)
    if not obj or obj:getPipedFuelAmount() <= 0 then
        return false
    end

    local square = obj:getSquare()
    return square and ((SandboxVars.AllowExteriorGenerator and square:haveElectricity()) or square:hasGridPower())
end

-- Check if a vehicle has a fuel tank that can be refilled (cistern or regular)
function W900CisternRefuel.getFuelTankPart(vehicle)
    local part = W900CisternParts.getGasTankPart(vehicle)
    if W900CisternParts.isSplitCisternVehicle(vehicle) then
        if W900CisternParts.isValidGasSourcePart(part) then
            return part
        end

        return nil
    end

    if part then
        return part
    end
    
    -- Fall back to regular gas tank
    part = vehicle:getPartById("GasTank")
    if part then
        return part
    end
    
    return nil
end

-- Find nearby fuel pump for any type of fuel tank
function W900CisternRefuel.getNearbyFuelPump(vehicle)
    local part = W900CisternRefuel.getFuelTankPart(vehicle)
    if not part then return nil end
    
    local areaCenter = vehicle:getAreaCenter(part:getArea())
    if not areaCenter then return nil end
    
    local square = getCell():getGridSquare(areaCenter:getX(), areaCenter:getY(), vehicle:getZ())
    if not square then return nil end
    
    -- Search in a 5x5 grid around the fuel tank
    for dy=-2,2 do
        for dx=-2,2 do
            local square2 = getCell():getGridSquare(square:getX() + dx, square:getY() + dy, square:getZ())
            if square2 and square2:getObjects() then
                for i=0, square2:getObjects():size()-1 do
                    local obj = square2:getObjects():get(i)
                    if isPoweredFuelPump(obj) then
                        return obj
                    end
                end
            end
        end
    end
    
    return nil
end

-- Refuel cistern from gas pump (5x faster than vanilla)
function W900CisternRefuel.onPumpGasoline(playerObj, part)
    if not W900CisternParts.isValidGasSourcePart(part) then
        return
    end

    if playerObj:getVehicle() then
        ISVehicleMenu.onExit(playerObj)
    end
    
    local fuelStation = W900CisternRefuel.getNearbyFuelPump(part:getVehicle())
    if fuelStation then
        local square = fuelStation:getSquare()
        if square then
            local action = ISPathFindAction:pathToVehicleArea(playerObj, part:getVehicle(), part:getArea())
            action:setOnFail(W900CisternRefuel.onPumpGasolinePathFail, playerObj)
            ISTimedActionQueue.add(action)
            
            -- Create refuel action and make it 5x faster
            local refuelAction = ISRefuelFromGasPump:new(playerObj, part, fuelStation)
            refuelAction.maxTime = refuelAction.maxTime / 5  -- 5x faster
            ISTimedActionQueue.add(refuelAction)
        end
    end
end

function W900CisternRefuel.onPumpGasolinePathFail(playerObj)
    playerObj:Say(getText("IGUI_PlayerText_CannotReachGasPump"))
end

-- Check if we can show the refuel option
function W900CisternRefuel.canRefuel(vehicle, playerObj)
    local part = W900CisternRefuel.getFuelTankPart(vehicle)
    if not part then return false end
    
    if part:getContainerContentAmount() >= part:getContainerCapacity() then
        return false
    end
    
    -- Check if there's a fuel pump nearby
    local fuelPump = W900CisternRefuel.getNearbyFuelPump(vehicle)
    if not fuelPump then return false end
    
    return true
end

function W900CisternRefuel.getNearbyFuelPumpFillTarget(vehicle)
    if not W900CisternContext or not W900CisternContext.getNearbyFuelPumpFillTarget then
        return nil
    end

    return W900CisternContext.getNearbyFuelPumpFillTarget(vehicle)
end

-- Hook into the vehicle radial menu
if not W900CisternRefuel.oldShowRadialMenu then
    W900CisternRefuel.oldShowRadialMenu = ISVehicleMenu.showRadialMenu
end

function ISVehicleMenu.showRadialMenu(playerObj)
    -- Call original function first
    W900CisternRefuel.oldShowRadialMenu(playerObj)
    
    -- Add cistern refuel option
    W900CisternRefuel.showRadialMenu(playerObj)
end

function W900CisternRefuel.showRadialMenu(playerObj)
    local vehicle = playerObj:getVehicle()
    if not vehicle then return end
    
    -- Only show if player is driver
    if not vehicle:isDriver(playerObj) then return end
    
    -- Check if this vehicle has a fuel tank we can refill
    local part = W900CisternRefuel.getFuelTankPart(vehicle)
    if not part then return end

    if part:getId() ~= "2000TankG" then
        -- Don't add cistern-specific options for regular gas tanks.
        return
    end

    local menu = getPlayerRadialMenu(playerObj:getPlayerNum())
    
    if W900CisternRefuel.canRefuel(vehicle, playerObj) then
        menu:addSlice(
            getText("ContextMenu_VehicleFillCisternTank") or "Fill Cistern Tank",
            getTexture("media/ui/vehicles/vehicle_refuel_from_pump.png"),
            W900CisternRefuel.onPumpGasoline,
            playerObj, part
        )
    end

    if part:getContainerContentAmount() > 0 then
        local fuelPumpTarget = W900CisternRefuel.getNearbyFuelPumpFillTarget(vehicle)
        if fuelPumpTarget then
            menu:addSlice(
                getText("ContextMenu_FillFuelPumpFromW900Cistern"),
                getTexture("media/textures/Icon_FuelPumpModded.png"),
                W900CisternContext.onFillFuelPumpFromCistern,
                playerObj,
                part,
                fuelPumpTarget
            )
        end
    end
end

----print(("W900: Cistern refueling system loaded")

return W900CisternRefuel
