local f = CreateFrame("Frame")
local ldb = LibStub:GetLibrary("LibDataBroker-1.1")
local dataobj = ldb:NewDataObject("Broker_Volumetric", {
  type = "data source",
  icon = [[Interface\COMMON\VOICECHAT-SPEAKER]],
  texcoord = {0, 0.8, 0, 1},
  iconCoords = {0, 0.8, 0, 1},
  text = "??%",
  OnClick = function () OptionsFrame_OpenToCategory(VideoOptionsFrame, "Sound") end,
})

f:RegisterEvent("VARIABLES_LOADED")

local function updateObject()
  local master = GetCVar("Sound_MasterVolume")
  local mastercol = GetCVar("Sound_EnableAllSound") == "0" and "|cffffaaaa" or "|r"
  
  local musicmute = GetCVar("Sound_EnableMusic") == "0" and "|cffddaaaaM" or ""

  local soundmute = ""
  local sfx, amb = GetCVar("Sound_EnableSFX"), GetCVar("Sound_EnableAmbience")
  if sfx == "0" and amb == "0" then
    soundmute = "|cffddaaaaS"
  elseif sfx == "0" then
    soundmute = "|cffddaaaaF"
  elseif amb == "0" then
    soundmute = "|cffddaaaaA"
  end
  
  dataobj.text = format("%s%s%s%d", soundmute, musicmute, mastercol, master * 100)
end

f:SetScript("OnEvent", function (self, event)
  updateObject()
end)

-- Sound_EnableAllSound  / Sound_MasterVolume
-- Sound_EnableSFX       / Sound_SFXVolume
-- Sound_EnableMusic     / Sound_MusicVolume
-- Sound_EnableAmbience  / Sound_AmbienceVolume

-- Sound_ToggleSound()       => Sound_EnableSFX, Sound_EnableAmbience
-- Sound_ToggleMusic()       => Sound_EnableMusic
-- Sound_MasterVolumeUp()    => Sound_MasterVolume
-- Sound_MasterVolumeDown()  => Sound_MasterVolume

hooksecurefunc("Sound_ToggleSound", updateObject)
hooksecurefunc("Sound_ToggleMusic", updateObject)
hooksecurefunc("Sound_MasterVolumeUp", updateObject)
hooksecurefunc("Sound_MasterVolumeDown", updateObject)

hooksecurefunc("SetCVar", function(cvar, value)
  --D("|cffaaaaffCVAR:|r |cffaaffaa"..cvar.."|r => |cffffaaaa"..value)
  if cvar == "Sound_EnableAllSound" or 
     cvar == "Sound_EnableSFX" or 
     cvar == "Sound_EnableAmbience" or
     cvar == "Sound_EnableMusic" or
     cvar == "Sound_MasterVolume" then
    updateObject()
  end
end)
