if isClient() then return end

local Commands = {}
local TowBarItemType = "TowBar.TowBar"

function Commands.attachConstraint(player, args)
    local vehicleA = args and getVehicleById(args.vehicleA)
    local vehicleB = args and getVehicleById(args.vehicleB)
    local attachmentA = args and args.attachmentA
    local attachmentB = args and args.attachmentB
    if not vehicleA or not vehicleB or not attachmentA or not attachmentB then return end

    vehicleA:addPointConstraint(player, vehicleB, attachmentA, attachmentB)
end

function Commands.detachConstraint(player, args)
    local vehicle = args and getVehicleById(args.vehicle)
    if not vehicle then return end

    vehicle:breakConstraint(true, false)
end

function Commands.consumeTowBar(player, args)
    if not player then return end
    local inventory = player:getInventory()
    if not inventory then return end

    local towBarItem = nil
    local itemId = args and args.itemId
    if itemId then
        towBarItem = inventory:getItemWithID(itemId)
    end
    if not towBarItem then
        towBarItem = inventory:getFirstTypeRecurse(TowBarItemType)
    end
    if not towBarItem then return end

    local wasPrimary = player:isPrimaryHandItem(towBarItem)
    local wasSecondary = player:isSecondaryHandItem(towBarItem)
    player:removeFromHands(towBarItem)
    inventory:Remove(towBarItem)
    sendRemoveItemFromContainer(inventory, towBarItem)

    if wasPrimary or wasSecondary then
        sendEquip(player)
    end
end

function Commands.giveTowBar(player, args)
    if not player then return end
    local inventory = player:getInventory()
    if not inventory then return end

    local towBarItem = inventory:AddItem(TowBarItemType)
    if not towBarItem then return end
    sendAddItemToContainer(inventory, towBarItem)

    if args and args.equipPrimary then
        player:setPrimaryHandItem(towBarItem)
        sendEquip(player)
    end
end

local function onClientCommand(module, command, player, args)
    if module ~= "towbar" then return end

    local fn = Commands[command]
    if fn then
        fn(player, args or {})
    end
end

Events.OnClientCommand.Add(onClientCommand)
