
settings = {}
local settingsSecurityStatus = false
local resourceName = getResourceName(getThisResource())

local settingsConfigList = {
    {
        func = function (value)
            value = tostring(value)
            return value:lower() == "true" and true or false
        end,
        key = "replacePlayerRockets"
    },
    {
        func = function (value)
            value = tostring(value)
            return value:lower() == "true" and true or false
        end,
        key = "replaceVehicleRockets"
    }
} 

function refreshSettings ()
    settings = {}
    for i=1, #settingsConfigList do
        local settingsConfig = settingsConfigList[i]
        local key = settingsConfig.key
        local func = settingsConfig.func
        
        local value = get(resourceName .. "." .. key)

        settings[key] = func and func(value) or value
    end
    return settings
end
refreshSettings ()


--[[
    Sync the settings value
]]

local settingsRawSet = toJSON(settings, true) -- toJSON to make value validation possible.

local resourceSettingsElement = createElement("resourceSettings")

function syncSettings ()
    if settingsSecurityStatus then
        removeEventHandler("onElementDataChange", resourceSettingsElement, checkIfSettingsSecurity)
        settingsSecurityStatus = false
    end
    setElementData(resourceSettingsElement, "settings", settings)
    if addEventHandler("onElementDataChange", resourceSettingsElement, checkIfSettingsSecurity , false) then
        settingsSecurityStatus = true
    end
end


--[[
    Security
]]


function checkIfSettingsSecurity (theKey, oldValue, newValue) 
    if theKey == "settings" then
        setElementData(resourceSettingsElement, "settings", settings)
        if client then
            outputServerLog ( "WARNING - Client " .. tostring(getPlayerName(client)) .. " tried to modify the resource settings of " .. getResourceName(getThisResource()))
            outputChatBox(tostring(getPlayerName(client)) .. " tried to cheat. See server logs.", root, 255, 0, 0)
        end
    end
end



--[[

    Updates

]]


local function escapePattern(text) 
    return text:gsub("([^%w])", "%%%1")
end
--[[
    Source: https://stackoverflow.com/questions/9790688/escaping-strings-for-gsub
]]



syncSettings()

addEventHandler( "onSettingChange", root, 
function (setting, oldValue, newValue) 
    if string.find(setting, "^\*" .. escapePattern(resourceName)) then
        refreshSettings ()
        syncSettings ()
    end
end, false)