local S = minetest.get_translator("audio_lib")



minetest.register_tool("audio_lib:settings", {
    description = S("Audio Settings"),
    inventory_image = "audiolib_settings.png",
    on_place = function() end,
    on_drop = function() end,

    on_use = function(itemstack, user, pointed_thing)
      local p_name = user:get_player_name()
      audio_lib.open_settings(p_name)
    end
})





----------------------------------------------
--------------------UTILS---------------------
----------------------------------------------

function audio_lib.open_settings(p_name)
  minetest.show_formspec(p_name, "audio_lib:p_settings", get_formspec(p_name))
end





----------------------------------------------
---------------FUNZIONI LOCALI----------------
----------------------------------------------

function get_formspec(p_name)
  local p_settings = audio_lib.get_settings(p_name)

  local formspec = {
    "formspec_version[4]",
    "size[13,4.1]",
    "bgcolor[;false]",
    "scrollbaroptions[max=100;smallstep=1;largestep=10;arrows=hide]",
    "hypertext[0.5,0.4;12,1;audio_settings;<global font=mono size=20 halign=center>" .. S("Audio Settings") .. "]",
    -- parametri
    "container[0.5,1.6]",
    "label[0,0;" .. S("Main") .. "]",
    "box[0,0.325;12,0.01;#a0938e]",
    "label[0,0.7;" .. S("BGM") .. "]",
    "container[5.5,0]",
    "label[0,0;0]",
    "label[5.75,0;100]",
    "scrollbar[0.4,-0.12;5.2,0.2;;volume_main;" .. p_settings.volume_main .. "]",
    "label[0,0.7;0]",
    "label[5.75,0.7;100]",
    "scrollbar[0.4,0.58;5.2,0.2;;volume_bgm;" .. p_settings.volume_bgm .. "]",
    "container_end[]",
    "container_end[]",
    "button[4.2,3.2;2,0.6;reset;" .. S("Reset") .. "]",
    "button[6.3,3.2;2,0.6;apply;" .. S("Apply") .."]",
  }

  return table.concat(formspec, "")
end





----------------------------------------------
---------------GESTIONE CAMPI-----------------
----------------------------------------------

minetest.register_on_player_receive_fields(function(player, formname, fields)
  if formname ~= "audio_lib:p_settings" then return end

  local p_name = player:get_player_name()

  if fields.reset then
    local settings = {
      volume_main = 100,
      volume_bgm = 100
    }

    audio_lib.save_settings(p_name, "_ALL_", settings)

    minetest.after(0, function()
      audio_lib.open_settings(p_name)
    end)

  -- applico il tutto
  elseif fields.apply then
    local settings = {
      volume_main = minetest.explode_scrollbar_event(fields.volume_main).value,
      volume_bgm = minetest.explode_scrollbar_event(fields.volume_bgm).value
    }

    audio_lib.save_settings(p_name, "_ALL_", settings)
    -- minetest.close_formspec(p_name, "audio_lib:p_settings")
  end
end)
