-- YAWL, Mails widget module
local mails = {}
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(_, path)

  -- base
  local t = base.txt()
  local w = base.bg()
  w:set_widget(t)

    -- base
  local t = base.txt()
  local w = base.bg()
  w:set_widget(t)

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

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

  -- watch func
  watch(
    'ls ' .. path, 5,
      function(_, stdout, stderr, exitreason, exitcode)
        -- count unread emails
        local counter = utils.lc(stdout)
        t:set_text(" " .. counter .. " ")

        -- set bg according to counter
        if (counter <= 0) then
          w:set_bg(beautiful.yawl_bg_ok)
        else
          w:set_bg(beautiful.yawl_bg_nok)
        end
      end,
    w
  )

  return widget

end

-- Return widget
return setmetatable(mails, mt)
