local awful = require("awful")
local gears = require("gears")
local wibox = require("wibox")
local awmtk = require("awmtk")

return function(args)
    local style = awmtk.style(awmtk.defaults, args.style or {},"battery_")
    local device = args.device or "default"
    local power_command = args.command or {"upower", "-d"}
    local icon = style.icon({
        {
            widget = wibox.widget.imagebox,
            image = style["battery_missing_symbolic"],
            id = "widget_icon",
            resize = true
        },
        (args.percentage and {
            widget = wibox.widget.textbox,
            markup = "0%",
            id = "widget_text"
        }),
        layout = wibox.layout.fixed.horizontal,
        spacing = style.battery_container_spacing_horizontal
    })
    gears.timer {
        autostart = true,
        timeout = 10,
        call_now = true,
        callback = function()
            awful.spawn.easy_async(power_command, function(out)
                local icon_name = out:match("icon%-name:%s+'(battery%-[^']+)'")
                local value = out:match("percentage:%s+(%d+%%)")
                icon:get_children_by_id("widget_icon")[1].image = 
                    style[(icon_name or ""):gsub("%-","_")] or 
                    style["battery_missing_symbolic"]
                if args.percentage and value then
                    icon:get_children_by_id("widget_text")[1].markup = value
                end
            end)
        end
    }
    return icon
end
