PlayerData = {}

if Config.framework ~= "esx" and (Config.framework ~= "auto" or GetResourceState("es_extended") ~= "started") then
	return
end

export, ESX = pcall(function()
	return exports.es_extended:getSharedObject()
end)

if not export then
	TriggerEvent("esx:getSharedObject", function(obj)
		ESX = obj
	end)
end

RegisterNetEvent("esx:playerLoaded")
AddEventHandler("esx:playerLoaded", function(xPlayer, isNew, skin)
	PlayerData = xPlayer

	ESX.PlayerLoaded = true

	TriggerEvent("electus_gangs:updateZones")
	TriggerEvent("electus_gangs:updateNextCaptureZones")

	TriggerEvent("electus_gangs:playerLoaded")
	OnPlayerLoad()
end)

RegisterNetEvent("esx:onPlayerLogout", function()
	ESX.PlayerLoaded = false

	while not ESX.PlayerLoaded do
		Wait(500)
	end

	FrameworkLoaded = true

	-- TriggerEvent("electus_gangs:updateZones")
	TriggerEvent("electus_gangs:updateNextCaptureZones")

	TriggerEvent("electus_gangs:playerLoaded")
	OnPlayerLoad()
end)

CreateThread(function()
	if not ESX.PlayerLoaded then
		return
	end

	Wait(500)

	while ESX == nil do
		Wait(500)
	end

	while ESX.GetPlayerData().job == nil do
		Wait(500)
	end

	PlayerData = ESX.GetPlayerData()
	TriggerEvent("electus_gangs:updateZones")
	TriggerEvent("electus_gangs:updateNextCaptureZones")

	TriggerEvent("electus_gangs:playerLoaded")
	OnPlayerLoad()
end)

RegisterNetEvent("esx:setJob")
AddEventHandler("esx:setJob", function(job)
	TriggerEvent("electus_gangs:zonesUpdated")
end)

function GetJobName()
	local job = ESX.GetPlayerData().job.name or ""

	return job
end

function GetIdentifier()
	local identifier = ESX.GetPlayerData().identifier

	return identifier
end

function ApplyVehicleMods(vehicleEnt, vehicle)
	if type(vehicle) == "string" then
		vehicle = json.decode(vehicle)
	end

	SetVehicleOnGroundProperly(vehicleEnt)
	SetVehicleNumberPlateText(vehicleEnt, vehicle.plate)

	ESX.Game.SetVehicleProperties(vehicleEnt, vehicle)

	if vehicle.damages then
		SetVehicleEngineHealth(vehicleEnt, vehicle.damages.engineHealth)
		SetVehicleBodyHealth(vehicleEnt, vehicle.damages.bodyHealth)
	end

	if vehicle.fuel then
		SetVehicleFuelLevel(vehicleEnt, vehicle.fuel)
	end
end

function GetVehicleMods(vehicleEnt)
	local mods = ESX.Game.GetVehicleProperties(vehicleEnt)
	return mods
end
