-- YAWL, Battery widget module
local battery = {}
local mt = {}

-- Requires
local wibox = require("wibox")
local base = require("yawl.base")
local utils = require("yawl.utils")
local beautiful = require("beautiful")
local watch = require("awful.widget.watch")

-- Entrypoint
function mt.__call()

  -- base txt widget
  local t = base.txt()
  local w = base.bg()
  w:set_widget(t)
  -- change default bg to battery full
  w:set_bg(beautiful.yawl_battery_full)

  -- icon widget
  local i = base.icon("")

  -- merge of the two
  local widget = wibox.widget {
    i,
    w,
    layout = wibox.layout.fixed.horizontal,
  }

  -- watch func
  watch(
    'acpi', 10,
    function(_, stdout, stderr, exitreason, exitcode)
      -- get lines for acpi
      local lines = utils.split(stdout, "[^\r\n]+")
      -- use first line (BAT0), get elements
      -- 1 : Battery
      -- 2 : :0
      -- 3 : State (Full, Discharching, Charging)
      -- 4 : Level (X%)
      local parts = utils.split(lines[1], "%S+")

      -- format data in dedicated vars
      local level = string.gsub(parts[4], "%%,?", "")
      local state = string.gsub(parts[3], ",", "")

      -- set background based on level
      if tonumber(level) >= 70 then
        i:set_text("  ")
        w:set_bg(beautiful.yawl_battery_full)
      elseif tonumber(level) >= 30 then
        i:set_text("  ")
        w:set_bg(beautiful.yawl_battery_mid)
      else
        i:set_text("  ")
        w:set_bg(beautiful.yawl_battery_low)
      end


      -- set state based on charging, full or discharching
      local st = ""
      if state == "Full" then
        st = ""
      elseif state == "Discharging" then
        st = ""
      elseif state == "Charging" then
        st = ""
      else
        st = ""
      end

      t:set_text(" " .. st .. " " .. level .. "% ")

    end,
    w
)

  return widget

end

-- Return widget
return setmetatable(battery, mt)