QBCore = exports['qb-core']:GetCoreObject()

local ActiveVan = -1
local ActiveItems = {}
local LastVan = nil
local totalVans = #Config.Gunvans.vehicles

math.randomseed(os.time())

local function firstLaunch()
    if not LastVan then
        LastVan = os.time()
    end
end
firstLaunch()


--Fordi laver du ActiveItems = Items, så laver den en REFERENCE istedet for at KOPIERE array'et over....
local function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else
        copy = orig
    end
    return copy
end

-- #### Spawn Van
local function spawnVan()
    if ActiveVan ~= -1 or Config.Debug then
        LastVan = os.time()
        if Config.perVanItems then
            ActiveItems = deepcopy(Config.Gunvans.vehicles[ActiveVan].items)
        else
            ActiveItems = deepcopy(Config.VanItems)
        end

        print("Van spawned at Coordinates: " ..
        Config.Gunvans.vehicles[ActiveVan].coords.x ..
        " " .. Config.Gunvans.vehicles[ActiveVan].coords.y .. " " .. Config.Gunvans.vehicles[ActiveVan].coords.z)

        TriggerClientEvent('_hp_gv:client:_spawnVan', -1, ActiveVan)
    end
end

-- #### Delete Van
local function deleteVan()
    Citizen.CreateThread(function()
        Citizen.Wait(Config.duration * 60000)
        ActiveVan = -1
        ActiveItems = {}
        TriggerClientEvent('_hp_gv:client:_destroyVan', -1)
        startCountdown()
    end)
end


-- #### Start Van countdown
function startCountdown()
    Citizen.CreateThread(function()
        Citizen.Wait(Config.minutesBetweenVans * 60000)
        ActiveVan = math.random(1, totalVans)
        spawnVan()
        deleteVan()
    end)

end
startCountdown()

-- #### Give Item
local function GiveItem(src, item)
    if ActiveItems[item].iAmount <= 0 then
        return Config.NotifyEmpty(src, ActiveItems[item].label)
    end

    local Player = QBCore.Functions.GetPlayer(src)

    if Player.Functions.GetMoney('cash') < ActiveItems[item].price then
        return Config.NotifyNoMoney(src, ActiveItems[item].label)
    end

    Player.Functions.RemoveMoney('cash', ActiveItems[item].price, 'Gun Van')

    Config.InventoryExport(src, ActiveItems[item].item, 1)
    if ActiveItems[item].weaponType == "pistol" then
        Config.InventoryExport(src, "pistol_ammo", ActiveItems[item].aAmount)
    end
    if ActiveItems[item].triggerCops then
        Config.EmergencyTrigger()
    end
    ActiveItems[item].iAmount = ActiveItems[item].iAmount - 1
    Config.Notify(src, ActiveItems[item].label)
end


-- #### Debug stuff
if Config.Debug then
    QBCore.Commands.Add('gv', '', {}, false, function(source, args)
        TriggerClientEvent('_hp_gv:client:_destroyVan', -1)
        ActiveVan = math.random(1, totalVans)
        spawnVan()
    end, Config.Permission)

    QBCore.Commands.Add('dgv', '', {}, false, function(source, args)
        ActiveVan = -1
        ActiveItems = {}
        TriggerClientEvent('_hp_gv:client:_destroyVan', -1)
    end, Config.Permission)
end

-- #### Server: Give Item
RegisterNetEvent('_hp_gv:server:_giveItem')
AddEventHandler('_hp_gv:server:_giveItem', function(item)
    local src = source
    local playerPed = GetPlayerPed(src)
    local Player = QBCore.Functions.GetPlayer(source)
    local playerCoords = GetEntityCoords(playerPed)
    local targetCoords = Config.Gunvans.vehicles[ActiveVan].coords

    if #(playerCoords - targetCoords) > 5.5 then
        Config.LogHandler(Player.PlayerData.citizenid .. " " .. Config.Lang.OutsideRange)
        Config.LogHandler("Distance: " .. #(playerCoords - targetCoords) .. " - Max distance: 5.5")

        if #(playerCoords - targetCoords) > 10 and Config.DropPlayer then
            Config.LogHandler("GunVan | " .. Player.PlayerData.citizenid .. " " .. Config.Lang.OutsideRangeKick)
            DropPlayer(src, Config.Lang.OutsideRangeKickPlayer)
        end

        return
    end

    if ActiveVan ~= -1 or Config.Debug then
        GiveItem(src, item)
    else
        Config.LogHandler("GunVan | " .. Player.PlayerData.citizenid .. " " .. Config.Lang.OutsideBuyHours)
        Config.LogHandler("GunVan | " ..
        Config.Lang.TimeUntilNext ..
        " " .. Config.minutesBetweenVans * 60 - (os.time() - LastVan) .. " " .. Config.Lang.Seconds)
        return
    end
end)
