local volume = {}

-- TODO: Refactor 'last_registered_signal'
local last_registered_signal

local DEFAULT_SIGNAL = "volume::value"

local vol = [[ str=$( pulsemixer --get-volume ); printf "$(pulsemixer --get-mute) ${str% *}\n" ]]

function volume.set_volume(val)
  -- awful.spawn.with_shell('killall pulsemixer; pulsemixer --set-volume ' .. tonumber(val))
  awful.spawn.with_shell('pulsemixer --set-volume ' .. tonumber(val))
  -- volume.emit(last_registered_signal)
end

function volume.toggle_mute()
  awful.spawn.with_shell('pulsemixer --toggle-mute ')
  volume.emit(last_registered_signal)
end

--- callback: function(is_muted, volume)
function volume.get(callback)
  awful.spawn.easy_async_with_shell(vol, function(out)
    local val = gears.string.split(out, " ")
    callback(tonumber(val[1]), tonumber(val[2]))
  end)
end

function volume.emit(name)
	volume.get(function(...)
		awesome.emit_signal(name or DEFAULT_SIGNAL, ...)
	end)
end

function volume.register_signal(signal_name, update_interval)
	last_registered_signal = signal_name or DEFAULT_SIGNAL
	gears.timer {
		timeout = update_interval or 5,
		call_now = true,
		autostart = true,
		callback = function() volume.emit(signal_name) end
	}
end

return volume
