dofile("data/scripts/lib/mod_settings.lua") -- see this file for documentation on some of the features.

function mod_setting_bool_custom( mod_id, gui, in_main_menu, im_id, setting )
	local value = ModSettingGetNextValue( mod_setting_get_id(mod_id,setting) )
	local text = setting.ui_name .. " - " .. GameTextGet( value and "$option_on" or "$option_off" )

	if GuiButton( gui, im_id, mod_setting_group_x_offset, 0, text ) then
		ModSettingSetNextValue( mod_setting_get_id(mod_id,setting), not value, false )
	end

	mod_setting_tooltip( mod_id, gui, in_main_menu, setting )
end

function mod_setting_change_callback( mod_id, gui, in_main_menu, setting, old_value, new_value  )
	print( tostring(new_value) )
end

local mod_id = "larpachaos" -- This should match the name of your mod's folder.
mod_settings_version = 1 -- This is a magic global that can be used to migrate settings to new mod versions. call mod_settings_get_version() before mod_settings_update() to get the old value.

local larpa_enable_options = {
  ["larpa_orbit"                                                 ]="Makes four copies of a projectile rotate around it",
  ["larpa_bounce"                                                ]="A projectile will launch a copy of itself when it bounces",
  ["larpa_explosion"                                             ]="A projectile will shoot out 8 copies of itself when it expires or hits the ground",
  ["larpa_trail"                                                 ]="Makes a projectile leave a trail of copies of itself",
  ["larpa_upwards"                                               ]="Makes a projectile cast copies of itself with an upwards trajectory",
  ["larpa_downwards"                                             ]="Makes a projectile cast copies of itself with a downwards trajectory",
  ["larpa_chaos"                                                 ]="Makes a projectile cast copies of itself in random directions",
}

local larpa_exclude_spawner_options = {
  ["data/entities/projectiles/orbspawner.xml"                    ]="Spiraalikalma's (blue phantom) orb spawner shots (spawned orbs will still larpa)",
  ["data/entities/projectiles/orbspawner_green.xml"              ]="Kiukkukalma's (green phantom) orb spawner shots (spawned orbs will still larpa)",
  ["data/entities/animals/boss_alchemist/wand_orb.xml"           ]="Ylialkemisti's wand orbs (these normally spawn the wand beams)",
  ["data/entities/projectiles/enlightened_laser_dark_wand.xml"   ]="Ylialkemisti's dark wand beam (spawned projectiles will still larpa)",
  ["data/entities/projectiles/enlightened_laser_elec_wand.xml"   ]="Ylialkemisti's electric wand beam (spawned projectiles will still larpa)",
  ["data/entities/projectiles/enlightened_laser_light_wand.xml"  ]="Ylialkemisti's light wand beam (spawned projectiles will still larpa)",
  ["data/entities/projectiles/enlightened_laser_fire_wand.xml"   ]="Ylialkemisti's fire wand beam (spawned projectiles will still larpa)",
  ["data/entities/projectiles/slimetrail.xml"                    ]="Toukka's slime trail (spawned slimeblobs will still larpa)",
  ["data/entities/projectiles/thunderball_line.xml"              ]="Suur-Ukko's thunderball trail (spawned slow thunderballs will still larpa)",
  ["data/entities/projectiles/megalaser_blue.xml"                ]="Jättilaser-lennokki (toaster) megalaser (spawned lasers will still larpa)",
  ["data/entities/animals/boss_robot/rocket_roll.xml"            ]="Kolmisilmän silmä (mecha kolmi) rocket roll (spawned missiles will still larpa)",
  ["data/entities/animals/boss_wizard/statusburst.xml"           ]="Mestarien mestari (MoM) status burst (spawned status orbs will still larpa)",
  ["data/entities/animals/boss_centipede/firepillar.xml"         ]="Kolmisilmä fire pillar (spawned firepillar parts will still larpa)",
  ["data/entities/animals/boss_centipede/orb_homing.xml"         ]="Kolmisilmä orb homing (spawned orb homing parts will still larpa)",
  ["data/entities/animals/boss_centipede/melee.xml"              ]="Kolmisilmä melee shots (spawned orb circleshots will still larpa)",
  ["data/entities/projectiles/pollen_ball.xml"                   ]="Huhtasieni (giga fungus) pollen ball (spawned pollen will still larpa)",
  ["data/entities/animals/boss_alchemist/projectile_counter.xml" ]="Ylialkemisti's counter shield",
}

local larpa_exclude_projectile_options = {
  ["data/entities/projectiles/darkflame_stationary.xml"          ]="Path of dark flame stationary trail",
  ["data/entities/projectiles/deck/glitter_bomb_explosion.xml"   ]="Glitter bomb explosion",
  ["data/entities/projectiles/deck/glitter_bomb_shrapnel.xml"    ]="Glitter bomb shrapnel",
  ["data/entities/projectiles/deck/spiral_part.xml"              ]="Spiral shot parts",
  ["data/entities/projectiles/thunderburst_thundermage.xml"      ]="Thunderball lightning burst",
  ["data/entities/projectiles/deck/spore_pod_growing.xml"        ]="Prickly spore pod growing",
  ["data/entities/projectiles/deck/spore_pod_spike.xml"          ]="Prickly spore pod spikes",
  ["data/entities/projectiles/deck/wall_builder.xml"             ]="Barrier wall",
  ["data/entities/projectiles/deck/wall_piece.xml"               ]="Barrier particles",
  ["data/entities/projectiles/deck/purple_explosion.xml"         ]="Glittering field explosions",
}

mod_settings = {
	{
		category_id = "cat_enable_larpa",
		ui_name = "Enable larpa",
		ui_description = "All valid projectiles will be larpa'ed",
--    foldable = true,
    _folded = true,
		settings = {},
  },
  {
		category_id = "cat_larpa_limit",
		ui_name = "Set Larpa limits",
		ui_description = "Turn off larpa When the # projectiles (within # radius) exceed this limit",
		settings = {
      {
        id = "limit_projectiles",
        ui_name = "Projectile limit",
        ui_description = "Number of projectiles",
        value_default = 1000,
        value_min = 100,
        value_max = 10000,
        scope = MOD_SETTING_SCOPE_RUNTIME,
      },
      {
        id = "limit_radius",
        ui_name = "Radius of effect",
        ui_description = "Effect radius from player",
        value_default = 370,
        value_min = 100,
        value_max = 500,
        scope = MOD_SETTING_SCOPE_RUNTIME,
      },
    },
  },
	{
		category_id = "cat_exclusion_mandatory",
		ui_name = "Practically mandatory exclusion list",
		ui_description = "These are enemy projectiles that spawn other projectiles",
    foldable = true,
    _folded = true,
		settings = {},
  },
  {
		category_id = "cat_exclusion_suggested",
		ui_name = "Suggested exclusion list",
		ui_description = "These are components of spell projectiles that are not normally subjected to the larpa spell modifier",
    foldable = true,
    _folded = true,
		settings = {},
  },
  {
		category_id = "cat_exclusion_other",
		ui_name = "Other exclusions",
		ui_description = "These are miscellaneous options",
    foldable = true,
    _folded = true,
		settings = {
      {
        id = "other_environment",
        ui_name = "Environmental traps",
        ui_description = "Projectiles that are generated by environmental traps (forcefield generator, arrow traps)",
        value_default = false,
        scope = MOD_SETTING_SCOPE_RUNTIME,
      },
      {
        id = "other_novelocity",
        ui_name = "Zero velocity environmental trap projectiles",
        ui_description = "Environmental trap projectiles that are have zero velocity (forcefield generator)",
        value_default = false,
        scope = MOD_SETTING_SCOPE_RUNTIME,
      },
    },
  },
	{
		id = "_",
		ui_name = "[For the exclude options, On = exclude]\nNOTE: A mod restart is required for settings changes to take effect",
		not_setting = true,
	},
}

local function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end

function table_invert(t)
  local s = {}
  for k,v in pairs(t) do
    s[v] = k
  end
  return s
end

local function pairsByValues (t, f)
  local a = {}
  local s = table_invert(t)
  for n in pairs(s) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if s[a[i]] == nil then return nil
    else return s[a[i]], a[i] 
    end
  end
  return iter
end

for k,v in pairsByKeys(larpa_enable_options) do
  local name = string.upper(string.sub(k,7,7)) .. string.sub(k,8,-1)
  local default = (k == "larpa_orbit" or k == "larpa_bounce" or k == "larpa_explosion" or k == "larpa_chaos")  
  table.insert(mod_settings[1].settings,{
    id = k,
    ui_name = name,
    ui_description = v,
    value_default = default,
    scope = MOD_SETTING_SCOPE_RUNTIME,
  })
end

for k,v in pairsByValues(larpa_exclude_spawner_options) do
  local basename = string.sub(string.match(k,"%b/."),2,-2)
  local name = string.upper(string.sub(basename,1,1)) .. string.gsub(string.sub(basename,2,-1),"_"," ")
  table.insert(mod_settings[3].settings,{
    id = k,
    ui_name = name,
    ui_description = v,
    value_default = true,
    scope = MOD_SETTING_SCOPE_RUNTIME,
  })
end

for k,v in pairsByValues(larpa_exclude_projectile_options) do
  local basename = string.sub(string.match(k,"%b/."),2,-2)
  local name = string.upper(string.sub(basename,1,1)) .. string.gsub(string.sub(basename,2,-1),"_"," ")
  table.insert(mod_settings[4].settings,{
    id = k,
    ui_name = name,
    ui_description = v,
    value_default = true,
    scope = MOD_SETTING_SCOPE_RUNTIME,
  })
end

function ModSettingsUpdate( init_scope )
	local old_version = mod_settings_get_version( mod_id ) -- This can be used to migrate some settings between mod versions.
	mod_settings_update( mod_id, mod_settings, init_scope )
end

function ModSettingsGuiCount()
	return mod_settings_gui_count( mod_id, mod_settings )
end

function ModSettingsGui( gui, in_main_menu )
	mod_settings_gui( mod_id, mod_settings, gui, in_main_menu )
end
