local awful = require("awful")
local wibox = require("wibox")
local naughty = require("naughty")

-- tooltip text function
local tooltip_text_format = [[
<b>%s (%s)</b>
Status:         %s
Charge:         %.1f%%
Health:         %.1f%%
Cycle Count:    %d
Rated Capacity: %.0fmAh (%.1fWh)
Voltage Min:    %.1fV
Voltage Now:    %.1fV
Technology:     %s
Manufacturer:   %s
Serial Number:  %s
]]

function bat_uevents()
	-- TODO io.popen will stop execution
	local uevents = io.popen("ls /sys/class/power_supply/*/uevent")
	local text = ""
	-- loop over uevent files
	for uevent in uevents:lines() do
		local ueventf = io.open(uevent)
		local ueventc = ueventf:read('a')
		ueventf:close()
		-- get attributes
		local a = {}
		for k, v in ueventc:gmatch("POWER_SUPPLY_(.-)=%s*(.-)\n") do
			a[k] = v
		end
		-- add to tooltip text
		if a.TYPE == "Battery" then
			local capacity = a.ENERGY_NOW * 100 / a.ENERGY_FULL
			local health = a.ENERGY_FULL * 100 / a.ENERGY_FULL_DESIGN
			local mah = a.ENERGY_FULL_DESIGN * 1000 / a.VOLTAGE_MIN_DESIGN
			text = text .. tooltip_text_format:format(
				a.NAME,
				a.MODEL_NAME,
				a.STATUS,
				capacity,
				health,
				a.CYCLE_COUNT,
				mah,
				a.ENERGY_FULL_DESIGN / 1000000,
				a.VOLTAGE_MIN_DESIGN / 1000000,
				a.VOLTAGE_NOW / 1000000,
				a.TECHNOLOGY,
				a.MANUFACTURER,
				a.SERIAL_NUMBER
			)
		end
	end
	uevents:close()
	if text == "" then
		return "No Batteries Installed"
	end
	return text
end

-- vars
local widget = wibox.widget.textbox()
local tooltip = awful.tooltip {
	objects = {widget},
	delay_show = 1,
	timeout = 2,
	timer_function = bat_uevents,
}

-- update widget on lowbat output
local lowbat_pid = awful.spawn.with_line_callback("lowbat", {
	stdout = function(stdout)
		widget:set_text(stdout)
	end,
	stderr = function(stderr)
		naughty.notify({
			preset = naughty.config.presets.critical,
			title = "lowbat error",
			text = stderr
		})
	end,
})

-- kill current lowbat on refresh/exit
awesome.connect_signal("exit", function() awful.spawn("kill " .. lowbat_pid) end)

return widget