-- luacheck: globals Character MyModGlobal LuaUserData Descriptors Timer CLIENT
if not CLIENT then return end

local dump = require("Cyka.dump")

-- LuaUserData.MakeMethodAccessible(Descriptors["Barotrauma.Sonar"], "UpdateGUIElements")

-- Make sure we have access to the Sonar enum types
-- LuaUserData.RegisterType(Descriptors["Barotrauma.Items.Components.Sonar+Mode"])

local function getSonarObjectInFocus()
	local character = Character.Controlled
	if not character then
		MyModGlobal.debugPrint("No controlled character")
		return nil, nil
	end

	local selectedItem = character.SelectedItem
	if not selectedItem then
		MyModGlobal.debugPrint("No selected item")
		return nil, nil
	end

	-- Check if the selected item is in fact the repairable object itself
	for _, component in pairs(selectedItem.Components) do
		if component.name == "Sonar" then
			return selectedItem, component
		end
	end

	return nil, nil
end

local function tryPing()
	local character = Character.Controlled
	if not character then
		MyModGlobal.debugPrint("No controlled character")
		return
	end

	local submarine = character.Submarine
	if not submarine then
		MyModGlobal.debugPrint("No submarine")
		return
	end

	local sonar, sonarComponent = getSonarObjectInFocus()
	if not sonar or not sonarComponent then
		MyModGlobal.debugPrint("No sonar or sonar component")
		return
	end

	local sonarButton = sonarComponent.SonarModeSwitch
	if not sonarButton then
		MyModGlobal.debugPrint("No sonar button")
		return
	end

	sonarButton.Selected = not sonarButton.Selected
	if sonarButton.Selected then
		-- Active
		sonarComponent.CurrentMode = 0
		Timer.Wait(function()
			sonarComponent.CurrentMode = 1
		end, 100)
	else
		-- Passive
		sonarComponent.CurrentMode = 1
	end
end

return {
	tryPing = tryPing,
}
