local wibox = require('wibox')
local awful = require('awful')
local gears = require('gears')
local theme = require('src.theme')
local volume = require('src.util.volume')

local volumeicon = wibox.widget.imagebox(theme.widget_vol_mute)
local volume_widget = wibox.widget.textbox()

local function spawn_callback(stdout)
    local volume_str = stdout:sub(9,12):gsub('[.]', '')
    local mute = stdout:match('MUTED')
    local level = tonumber(volume_str)
    if level == nil then
        volume_widget:set_markup('Waiting')
        return
    end
    if mute then
        volumeicon:set_image(theme.widget_vol_mute)
    elseif level == 0 then
        volumeicon:set_image(theme.widget_vol_mute)
    elseif level <= 50 then
        volumeicon:set_image(theme.widget_vol_low)
    else
        volumeicon:set_image(theme.widget_vol_high)
    end
    volume_widget:set_markup(level .. (mute  and 'M' or '%'))
end

local function timer_callback()
    awful.spawn.easy_async('wpctl get-volume @DEFAULT_AUDIO_SINK@', spawn_callback)
end

local volume_timer = gears.timer {
    timeout = 30,
    autostart = true,
    call_now = true,
    callback = timer_callback
}

awesome.connect_signal(volume.volume_changed_signal, function() volume_timer:emit_signal('timeout') end)

local volumebuttons = awful.util.table.join(
    awful.button({}, 1, volume.toggle_mute),
    awful.button({}, 4, volume.vol_up),
    awful.button({}, 5, volume.vol_down)
)

volume_widget:buttons(volumebuttons)
volumeicon:buttons(volumebuttons)

return { wibox.layout.fixed.horizontal(volumeicon, volume_widget) }