local awful = awful
local beautiful = beautiful
local client = client
local ext = require("ext")
local lfs = require("lfs")
local pairs = pairs
local string = string
local table = table
local widget = widget

module("oni")

local maildirfmt = "/home/slash/documents/mail/%s/inbox/new/"

function mailcount(account)
   local i = 0
   local dir = string.format(maildirfmt, account)

   for file in lfs.dir(dir) do
      if file ~= "." and file ~= ".." then
         i = i + 1
      end
   end

   return i
end

local function showmail(name)
   awful.util.spawn("emacsclient -e '(oni:view-mail \"" .. name .. "\")'")
end

function mailcount_widgets(label, account, name)
   widgets = {}
   widgets.label = widget({ type = "textbox" })
   widgets.label.text = string.format(" %s: ", label)
   widgets.count = widget({ type = "textbox" })
   widgets.count.text = string.format(" %d ", mailcount(account))
   widgets.count.bg = beautiful.bg_focus
   widgets.count:buttons(
      awful.util.table.join(
         awful.button({ }, 1, function (c) showmail(name) end)))

   return widgets
end

function focus_raise(direction)
   awful.client.focus.bydirection(direction)
   if client.focus then client.focus:raise() end
end

function ror_browser()
   ext.run_or_raise("conkeror", { class = "Conkeror" })
end

function ror_editor()
   ext.run_or_raise("emacsclient -c -a emacs", { class = "Emacs" })
end

function ror_term()
   ext.run_or_raise("urxvt", { class = "URxvt" })
end

function run_browser()
   awful.util.spawn("conkeror")
end

function run_editor()
   awful.util.spawn("emacsclient -c -a emacs")
end

function run_term()
   awful.util.spawn("urxvt")
end