UISettings = {}

-- Create a meta table to get basic Class-like behavior
local UISettings_mt = Class(UISettings)

---Creates the settings UI object
---@return SettingsUI @The new object
function UISettings.new()
    local self = setmetatable({}, UISettings_mt)

    self.controls = {}
	self.settings = g_additionalContractTypes.settings	
		
    return self
end

---Register the UI into the base game UI
function UISettings:registerSettings()
    -- Get a reference to the base game general settings page
    local settingsPage = g_gui.screenControllers[InGameMenu].pageSettings
	
	-- Define the UI controls. For each control, a <prefix>_<name>_title and _info key must exist in the i18n values
    local controlProperties = g_additionalContractTypes.controls;

    UIHelper.createControlsDynamically(settingsPage, "ui_setting_title", self, controlProperties, "ui_")
    UIHelper.setupAutoBindControls(self, self.settings, UISettings.onSettingsChange)

    -- Apply initial values
    self:updateUiElements()

    -- Update any additional settings whenever the frame gets opened
    InGameMenuSettingsFrame.onFrameOpen = Utils.appendedFunction(InGameMenuSettingsFrame.onFrameOpen, function()
        self:updateUiElements(true) -- We can skip autobind controls here since they are already registered to onFrameOpen
    end)
	
	-- Trigger to update the values when settings frame is closed
	InGameMenuSettingsFrame.onFrameClose = Utils.appendedFunction(InGameMenuSettingsFrame.onFrameClose, function()
		self:onFrameClose();
   	end);

end

function UISettings:onSettingsChange(control)    
	if control ~= nil and control.name ~= nil then
		local state = g_additionalContractTypes.settings[control.name];
		if state ~= nil then			
			if g_additionalContractTypes.typ[control.typName] ~= nil and g_additionalContractTypes.typ[control.typName].changeSettingsEvent ~= nil then
				g_additionalContractTypes.typ[control.typName]:changeSettingsEvent(control.name, state);					
			elseif control.typName == "additionalContract" then
				g_additionalContractTypes:changeSettingsEvent(control.name, state);
			end;		
		end;
	end;
	self:updateUiElements()
end;

---Updates the UI elements to reflect the current settings
---@param skipAutoBindControls boolean|nil @True if controls with the autoBind properties shall not be newly populated
function UISettings:updateUiElements(skipAutoBindControls)
    if not skipAutoBindControls then
        -- Note: This method is created dynamically by UIHelper.setupAutoBindControls
        self.populateAutoBindControls()
    end

	local isAdmin = g_currentMission:getIsServer() or g_currentMission.isMasterUser

	for _, control in ipairs(self.controls) do
		control:setDisabled(not isAdmin)
	end
	
    -- Update the focus manager
    local settingsPage = g_gui.screenControllers[InGameMenu].pageSettings
    settingsPage.gameSettingsLayout:invalidateLayout()
end

function UISettings:onFrameClose()
	
end