-- YAWL, Pomodoro widget module
-- Using calabash
local pomodoro = {}
local mt = {}

-- Requires
local wibox = require("wibox")
-- Requires dkjson as external module
local json = require("dkjson")
local beautiful = require("beautiful")
local watch = require("awful.widget.watch")
local base = require("yawl.base")

-- 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_pomodoro_absent)

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

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

  -- watch func
  watch(
    'clbsh status', 3,
    function(_, stdout, stderr, exitreason, exitcode)

        local current = 0
        local remaining = 0

        if exitcode ~= 0 then
          w:set_bg(beautiful.yawl_pomodoro_absent)
          w:set_fg(beautiful.yawl_fg_normal)
          t:set_text(" none ")
          return
        end

        w:set_fg(beautiful.yawl_fg)

        local decode, pos, err = json.decode(stdout)
        if err then
          t:set_text(" error decoding json ")
          return
        end

        if decode.status == 0 then
          w:set_bg(beautiful.yawl_pomodoro_working)
          current = decode.pomodori
        else
          w:set_bg(beautiful.yawl_pomodoro_break)
          current = decode.breaks
        end

        if decode.paused == true then
          w:set_bg(beautiful.yawl_pomodoro_paused)
        end

        if tonumber(decode.remaining) == 1 then
          remaining = "hurry up !"
        else
          remaining = decode.remaining
        end

        t:set_text(" " .. current .. " / " .. remaining .. " ")

    end,
    w
)

  return widget

end

-- Return widget
return setmetatable(pomodoro, mt)
