local mod = get_mod("granular_settings")

local InputSettings = require("scripts/settings/options/input_settings")
local input_settings_by_id = InputSettings.settings_by_id
local RenderSettings = require("scripts/settings/options/render_settings")
local gameplay_fov = RenderSettings.settings_by_id.gameplay_fov

for k,v in pairs(input_settings_by_id) do
    if string.find(k, "mouse_look_scale") then
        v.step_size = 10^-6
        v.min_value = v.step_size
        v.normalized_step_size = v.step_size / (v.max_value - v.min_value)
        v.explode_function = function (normalized_value)
            local exploded_value = v.min_value + normalized_value * (v.max_value - v.min_value)
            exploded_value = math.round(exploded_value / v.step_size) * v.step_size
            return exploded_value
        end
        v.format_value_function = function (value)
            local number_format = string.format("%%.%sf", 6)
            local result = string.format(number_format, value)
            return result
        end
    end
end

gameplay_fov.num_decimals = 6
gameplay_fov.step_size_value = 10^(-gameplay_fov.num_decimals)
gameplay_fov.min_value = 1
gameplay_fov.max_value = 179

mod:command("set_look_scale", mod:localize("sensitivity_description"), function(s, ...)
    s = tonumber(s)
    if s == nil or s < 10^-6 or s > 10 then
        mod:error("Invalid")
        return
    end
    input_settings_by_id.mouse_look_scale.on_activated(s)
    input_settings_by_id.mouse_look_scale_ranged.on_activated(s)
    input_settings_by_id.mouse_look_scale_ranged_alternate_fire.on_activated(s)
end)

mod:command("set_look_scale_ranged", mod:localize("sensitivity_description"), function(s, ...)
    s = tonumber(s)
    if s == nil or s < 10^-6 or s > 10 then
        mod:error("Invalid")
        return
    end
    input_settings_by_id.mouse_look_scale_ranged.on_activated(s)
    input_settings_by_id.mouse_look_scale_ranged_alternate_fire.on_activated(s)
end)

mod:command("set_look_scale_ranged_alternate_fire", mod:localize("sensitivity_description"), function(s, ...)
    s = tonumber(s)
    if s == nil or s < 10^-6 or s > 10 then
        mod:error("Invalid")
        return
    end
    input_settings_by_id.mouse_look_scale_ranged_alternate_fire.on_activated(s)
end)

mod:command("set_vertical_fov", mod:localize("fov_description"), function(f, ...)
    f = tonumber(f)
    if f == nil or f < 1 or f > 179 then
        mod:error("Invalid")
        return
    end

    gameplay_fov.on_activated(f, gameplay_fov)
end)

mod:command("set_horizontal_fov", mod:localize("fov_description"), function(f, ...)
    f = tonumber(f)
    if f == nil or f < 1 or f > 179 then
        mod:error("Invalid")
        return
    end
    
    local aspect_ratio = RESOLUTION_LOOKUP.width / RESOLUTION_LOOKUP.height
    local f = 2 * math.deg(math.atan(math.tan(math.rad(f/2)) / aspect_ratio))

    gameplay_fov.on_activated(f, gameplay_fov)
end)
