---@diagnostic disable: inject-field, param-type-mismatch, undefined-field
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by my phus cyaches.
--- DateTime: 9/21/2022 9:05 PM
--- Taken from original PZcode removeburntvehicle in vehicle lua

require "Vehicles/ISUI/ISVehicleMenu"
require "luautils"
require "VRO_SalvageSandbox"

local function _tag(id)
    if id == nil then return nil end
    -- already an ItemTag?
    if type(id) == "userdata" and id.getId then return id end

    local function _rl(s)
        s = tostring(s)
        if not s:find(":", 1, true) then s = "base:" .. s end
        if ResourceLocation and ResourceLocation.of then
            return ResourceLocation.of(s)
        elseif ResourceLocation and ResourceLocation.new then
            local ns, path = s:match("^([^:]+):(.+)$")
            return ResourceLocation.new(ns or "base", path or s)
        end
        return nil
    end

    if ItemTag and ItemTag.get then
        local rl = _rl(id)
        if rl then
            local ok, tag = pcall(function() return ItemTag.get(rl) end)
            if ok and tag then return tag end
        end
    end
    -- fallback for older builds
    return id
end

local enableSalvage = ISVehicleMenu.FillMenuOutsideVehicle
-- Prefer an already-worn item that matches a tag (e.g., WeldingMask)
local function getWornMatchingTag(chr, tag)
    local worn = chr and chr:getWornItems()
    if not worn then return nil end
    for i = 0, worn:size()-1 do
        local wi = worn:get(i)
        local it = wi and wi:getItem() or nil
        if it and it.hasTag and it:hasTag(_tag(tag)) then return it end
    end
    return nil
end

local function _getScriptsForTag(tag)
    local sm = ScriptManager and ScriptManager.instance
    if not sm then return nil end
    local T = _tag(tag)
    if sm.getItemsTag then
        return sm:getItemsTag(T)
    elseif sm.getAllItemsWithTag then
        return sm:getAllItemsWithTag(T)
    end
    return nil
end

-- Build a red "One of:" list for a missing tag (e.g., WeldingMask)
local function appendOneOfForTag(desc, tag)
    local arr = _getScriptsForTag(tag)

    -- Header
    desc = desc .. " <LINE> <RGB:1,0,0> " .. getText("IGUI_CraftUI_OneOf") .. " <LINE> "

    if arr and arr.size and arr:size() > 0 then
        for i = 1, arr:size() do
            local si = arr:get(i-1)
            local ft = (si.getFullName and si:getFullName())
                    or (si:getModule():getName() .. "." .. si:getName())
            local nm = (getItemNameFromFullType and getItemNameFromFullType(ft))
                    or (si.getDisplayName and si:getDisplayName())
                    or ft

            desc = desc .. " <INDENT:20> <RGB:1,0,0> " .. nm .. " 0/1 <INDENT:0> "
            if i < arr:size() then
                desc = desc .. " <LINE> "
            end
        end
    else
        -- Fallback line if the tag has no scripts found
        local nm = getText("ContextMenu_WeldingMask")
        desc = desc .. " <INDENT:20> <RGB:1,0,0> " .. nm .. " 0/1 <INDENT:0> "
    end
    return desc
end

local function predicateBlowTorch(item)
    return (item ~= nil) and
            ((item.hasTag and item:hasTag(_tag("BlowTorch"))) or item:getType() == "BlowTorch") and
            (item:getCurrentUses() >= 10)
end

local function comparatorDrainableUsesInt(item1, item2)
	return item1:getCurrentUses() - item2:getCurrentUses()
end

local function valhallaclaimed(vehicle)
    ---Thanks Udderly for letting me poke around your code for ideas---
    if not (Valhalla and Valhalla.VehicleClaims) then
        return false
    end

    local claimed = nil

    if Valhalla:getVehicleModData(vehicle) then
        claimed = Valhalla:getVehicleModData(vehicle)
    else
        return false
    end

    if claimed then
        local owner = claimed["owner"]
        if owner and owner ~= "" then
            return claimed["owner"]
        end
    end
end

function ISVehicleMenu.onVehicleSalvage(player, vehicle)
    if luautils.walkAdj(player, vehicle:getSquare()) then
        ISWorldObjectContextMenu.equip(player, player:getPrimaryHandItem(), predicateBlowTorch, true);

        -- Prefer already-worn protective gear if it satisfies WeldingMask
        local wornMask = getWornMatchingTag(player, "WeldingMask")
        if not wornMask then
            local mask = player:getInventory():getFirstTagRecurse(_tag("WeldingMask"))
            if mask then
                ISInventoryPaneContextMenu.wearItem(mask, player:getPlayerNum())
            end
        end
        ISTimedActionQueue.add(ISVehicleSalvage:new(player, vehicle));
    end
end

function ISVehicleMenu.FillMenuOutsideVehicle(player, context, vehicle, test)

    local playerObj = getSpecificPlayer(player)
    local MWSkill = 4
    local MWSkillDisplay = playerObj:getPerkLevel(Perks.MetalWelding)
    local MecSkill = 3
    local MecSkillDisplay = playerObj:getPerkLevel(Perks.Mechanics)
    local isClaimed = valhallaclaimed(vehicle)
    --[[
        local subOption = context:addOption("Vehicle")
        local vehicleMenu = ISContextMenu:getNew(context)
        context:addSubMenu(subOption, vehicleMenu)
        vehicleMenu:addOption("Info", playerObj, ISVehicleMenu.onInfo, vehicle)
    --]]
    --	context:addOption("Vehicle Info", playerObj, ISVehicleMenu.onInfo, vehicle)

    local option = nil
    --- remove Salvage Vehicles options ---
    if SandboxVars.VehicleRepairOverhaul == true or string.match(vehicle:getScript():getName(), "Burnt") or isClaimed then return enableSalvage(player, context, vehicle, test) end;
    if VRO and VRO.IsFullVehicleSalvagingEnabled and (VRO.IsFullVehicleSalvagingEnabled() == false) then
        return enableSalvage(player, context, vehicle, test)
    end

    ---Salvage complete vehicles add option to menu---
        option = context:addOption(getText("ContextMenu_SalvageVehicle"), playerObj, ISVehicleMenu.onVehicleSalvage, vehicle);
        local toolTip = ISToolTip:new();
        toolTip:initialise();
        toolTip:setVisible(false);
        option.toolTip = toolTip;
        toolTip:setName(getText("ContextMenu_SalvageVehicle"));
        toolTip.description = getText("Tooltip_SalvageVehicle") .. " <LINE> <LINE> " .. getText("Tooltip_craft_Needs") .. " : <LINE> ";

        local blowTorch = playerObj:getInventory():getBestTypeEvalRecurse("Base.BlowTorch", comparatorDrainableUsesInt)
        if blowTorch then
            local blowTorchUseLeft = blowTorch:getCurrentUses();
            if blowTorchUseLeft >= 10 then
                toolTip.description = toolTip.description .. " <LINE> <RGB:0,1,0> " .. getItemNameFromFullType("Base.BlowTorch") .. " " .. getText("ContextMenu_Uses") .. " " .. blowTorchUseLeft .. "/" .. 10;
            else
                toolTip.description = toolTip.description .. " <LINE> <RGB:1,0,0> " .. getItemNameFromFullType("Base.BlowTorch") .. " " .. getText("ContextMenu_Uses") .. " " .. blowTorchUseLeft .. "/" .. 10;
                option.notAvailable = true;
            end
        else
            toolTip.description = toolTip.description .. " <LINE> <RGB:1,0,0> " .. getItemNameFromFullType("Base.BlowTorch") .. " 0/10";
            option.notAvailable = true;
        end

        local inventory = playerObj:getInventory()
        local maskTag   = "WeldingMask"
        local wornMask = getWornMatchingTag(playerObj, maskTag)
        if wornMask then
            local displayName = (wornMask.getDisplayName and wornMask:getDisplayName())
                                or getText("ContextMenu_WeldingMask")
                                or "Welder Mask"
            toolTip.description = toolTip.description .. " <LINE> <RGB:0,1,0> " .. displayName .. " 1/1"
        else
            -- Fall back to inventory
            local maskItem = inventory:getFirstTagRecurse(_tag(maskTag))
            if maskItem then
                local displayName = (maskItem.getDisplayName and maskItem:getDisplayName()) or getText("ContextMenu_WeldingMask") or "Welder Mask"
                toolTip.description = toolTip.description .. " <LINE> <RGB:0,1,0> " .. displayName .. " 1/1"
            else
                -- None at all → show One Of list and mark unavailable
                option.notAvailable = true
                toolTip.description = appendOneOfForTag(toolTip.description, maskTag)
            end
        end

        if playerObj:getPerkLevel(Perks.MetalWelding) >= MWSkill then
            toolTip.description = toolTip.description .. " <LINE> <RGB:0,1,0> " .. getText("IGUI_perks_MetalWelding") .. " " .. MWSkillDisplay .. "/" .. 4;
        else
            toolTip.description = toolTip.description .. " <LINE> <RGB:1,0,0> " .. getText("IGUI_perks_MetalWelding") .. " " .. MWSkillDisplay .. "/" .. 4;
            option.notAvailable = true;
        end

        if playerObj:getPerkLevel(Perks.Mechanics) >= MecSkill then
            toolTip.description = toolTip.description .. " <LINE> <RGB:0,1,0> " .. getText("IGUI_perks_Mechanics") .. " " .. MecSkillDisplay .. "/" .. 3;
        else
            toolTip.description = toolTip.description .. " <LINE> <RGB:1,0,0> " .. getText("IGUI_perks_Mechanics") .. " " .. MecSkillDisplay .. "/" .. 3;
            option.notAvailable = true;
        end

    enableSalvage(player, context, vehicle, test)
end