-- YAWL, Spotify widget module
local spotify = {}
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
  local t = base.txt()
  local w = base.bg()
  w:set_widget(t)
  -- change default bg to paused
  w:set_bg(beautiful.yawl_spotify_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(
    -- is spotify running ?
    'pidof spotify', 5,
    function(_, stdout, stderr, exitreason, exitcode)

      if stdout == "" then
        w:set_bg(beautiful.yawl_spotify_absent)
        w:set_fg(beautiful.yawl_spotify_absent_fg)
        t:set_text(" not running ")
        return
      end

      w:set_fg(beautiful.yawl_fg)
      local status = utils.sanitize(utils.run("playerctl -p spotify status"))
      local np = utils.sanitize(utils.run('playerctl -p spotify metadata --format="{{ artist }} · {{ title }}"'))

      if status == "Playing" then
        w:set_bg(beautiful.yawl_spotify_play)
      else
        w:set_bg(beautiful.yawl_spotify_pause)
      end

      t:set_text(" " .. np .. " ")

    end,
    w
  )

  return widget

end

-- Return widget
return setmetatable(spotify, mt)
