if isClient() then
	return print("WARN: Sandbox Options available only for singleplayer.")
end


STAR_MODS = STAR_MODS or {}
if STAR_MODS.ChangeSandboxSettings then
	return print('ERROR: There are two mods ChangeSandboxSettings!')
end
STAR_MODS.ChangeSandboxSettings = {}


local core = getCore()
local _ver = core.getVersionNumber and core:getVersionNumber() or core:getVersion()
if _ver < "41.78" then
	return print("WARN: Sandbox Options available only for 41.78+")
end


local function InGame()
	local inst = MainScreen.instance
	return inst and inst.inGame
end

local old_settingsFromUI = ISServerSandboxOptionsUI.settingsFromUI
function ISServerSandboxOptionsUI:settingsFromUI(options, ...)
	old_settingsFromUI(self, options, ...)
	for i=1,options:getNumOptions() do
		local option = options:getOptionByIndex(i-1)
		local control = self.controls[option:getName()]
		if control then
			getSandboxOptions():set(option:getName(),option:getValue())
			--wwwoption = option
			local cat = option:getTableName()
			local var = option:getShortName()
			local val = option:getValue()
			--print('Option = ',cat,var,val)
			if cat then
				SandboxVars[cat][var] = val
			else
				SandboxVars[var] = val
			end
		end
	end
end

--[[ custom event OnSandboxOptionsChanged
EXAPLE:
if Events.OnSandboxOptionsChanged then
	Events.OnSandboxOptionsChanged.Add(function()
		print('Sandbox Options have been changed!')
	end)
end
--]]
do
	local fns = {}
	Events.OnSandboxOptionsChanged = {
		fns = fns,
		Add = function(fn)
			fns[fn] = true
		end,
		Remove = function(fn)
			fns[fn] = nil
		end,
		Trigger = function()
			for fn in pairs(fns) do
				pcall(fn)
			end
		end,
	}

	local old_setVisible = ISServerSandboxOptionsUI.setVisible
	function ISServerSandboxOptionsUI:setVisible(bool, ...)
		old_setVisible(self, bool, ...)
		if bool == false then
			Events.OnSandboxOptionsChanged.Trigger()
		end
	end

end

local MakePause; MakePause = function()
	Events.OnTickEvenPaused.Remove(MakePause)
	local controls = UIManager.getSpeedControls()
	if controls then
		controls:SetCurrentGameSpeed(0)
	end
end

local function ShowSandboxOptions()
	if ISServerSandboxOptionsUI.instance then
		ISServerSandboxOptionsUI.instance:close()
	end
	local old_ui = ISServerSandboxOptionsUI.instance
	local ui = old_ui or ISServerSandboxOptionsUI:new(150, 150,800, 600)
	if old_ui then
		ui:setVisible(true)
	else
		ui:initialise()
		ui:addToUIManager()
	end
	if SandboxVars.ChangeSandboxOptions.Pause == 2 then
		Events.OnTickEvenPaused.Add(MakePause)
	end
end



-- Fix main menu option

local function MouseButtonDown(item, x, y)
	ShowSandboxOptions()
	local self = MainScreen.instance
	if self and self.returnOption then -- RETURN
		MainScreen.onMenuItemMouseDownMainMenu(self.returnOption,0,0)
	end
end

local old_MainScreen_instantiate = MainScreen.instantiate
function MainScreen:instantiate()
	old_MainScreen_instantiate(self)
	local labelY = self.bottomPanel:getHeight()
	local labelX = self.exitOption and self.exitOption:getX() or 0
	local labelSeparator = 16
	local labelHgt = getTextManager():getFontHeight(UIFont.Large) + 8 * 2
	if self.inGame then
		labelY = labelY + labelSeparator
		self.sb_options = ISLabel:new(labelX, labelY, labelHgt, getText("UI_optionscreen_SandboxOptions"), 1, 1, 1, 1, UIFont.Large, true);
		self.sb_options.internal = "SANDBOX_OPTIONS";
		self.sb_options:initialise();
		self.bottomPanel:addChild(self.sb_options);
		self.sb_options.onMouseDown = MouseButtonDown;
		labelY = labelY + labelHgt
		self.bottomPanel:setHeight(labelY)
		if self.exitOption and self.quitToDesktop then
			local save_y = self.exitOption:getY()
			self.exitOption:setY(self.quitToDesktop:getY())
			self.quitToDesktop:setY(self.sb_options:getY())
			self.sb_options:setY(save_y)
		end
	end
end

Events.OnGameStart.Add(function()
	ISServerSandboxOptionsUI.removeFromUIManager = function()end
	local old_destroy = ISServerSandboxOptionsUI.destroy
	function ISServerSandboxOptionsUI:destroy()
		old_destroy(self)
		self:setVisible(false)
	end
end)



---- Hotkey -----
if ModOptions and ModOptions.AddKeyBinding then

	local key_data = {
		key = Keyboard.KEY_NONE,  --default
		name = "SANDBOX_HOTKEY",  -- just id (user won't see this name)
	}

	local category = "[UI]";
	ModOptions:AddKeyBinding(category, key_data);

	local function KeyUp(keynum)
		if keynum == key_data.key then
			if not InGame() then
				return
			end
			print("Hello! You've pressed 2 on the numpad!")
			ShowSandboxOptions()
		end
	end
	Events.OnKeyPressed.Add(KeyUp)
end



---------- FIX THE UI PATCH ----------

if STAR_MODS.FixVanillaOptionsUI42 and STAR_MODS.FixVanillaOptionsUI42.version >= 1.0 then
	return
end
STAR_MODS.FixVanillaOptionsUI42 = {
	version = 1.0,
}

local function ForcedSetY(self, y)
	self.y = y;
	if self.javaObject ~= nil then
		self.javaObject:setY(y);
	end
end

local old_createPanel = ISServerSandboxOptionsUI.createPanel
local function new_createPanel(self, ...)
	local old_setY = ISUIElement.setY
	ISUIElement.setY = ForcedSetY
	local status, panel = pcall(old_createPanel, self, ...)
	ISUIElement.setY = old_setY
	return panel
end
ISServerSandboxOptionsUI.createPanel = new_createPanel

function STAR_MODS.FixVanillaOptionsUI42.CancelFix()
	if ISServerSandboxOptionsUI.createPanel ~= new_createPanel then
		print('ChangeSandboxOptions: WARNING! createPanel was changed by another mod!')
	end
	ISServerSandboxOptionsUI.createPanel = old_createPanel
end




