# Spotify sublet file
# Created with sur-0.2
require "dbus"

configure :spotify do |s|
  s.interval = 30

  # Icons
  s.icons = {
    :Play      => Subtlext::Icon.new("play.xbm"),
    :Pause     => Subtlext::Icon.new("pause.xbm"),
    :Stop      => Subtlext::Icon.new("stop.xbm"),
    :Previous  => Subtlext::Icon.new("prev.xbm"),
    :Next      => Subtlext::Icon.new("next.xbm"),
    :Note      => Subtlext::Icon.new("note.xbm")
  }

  # Create DBus session
  dbus     = DBus::SessionBus.instance
  service  = dbus.service("org.mpris.MediaPlayer2.spotify")
  s.player = service.object("/org/mpris/MediaPlayer2")

  s.player.introspect

  s.state  = :Stop
end

on :run do |s|
  update_status
end

helper do |s| # {{{
  def toggle_state # {{{
    case self.state
      when :Stop  then :Play
      when :Pause then :Play
      when :Play  then :Pause
    end
  end # }}}

  def send_action(action) # {{{
    self.state = action unless [ :Previous, :Next ].include? action

    self.player.send(action)
  end # }}}

  def update_status # {{{
    icon = :play

    # Select icon based on state
    case self.state
      when :Play  then icon = :Pause
      when :Pause then icon = :Play
      when :Stop  then icon = :Play
    end

    # Fetch current track
    track_if_any = "None"

    begin
      meta = player.Get("org.mpris.MediaPlayer2.Player", "Metadata")

      track_if_any = "%s - %s" % [ 
        meta.first["xesam:artist"].first, 
        meta.first["xesam:title"]
      ]
    rescue
      track_if_any = "None"
    end

    # Finally assemble status line
    self.data = "%s%s%s%s %s%s" % [
      self.icons[:Previous],
      self.icons[icon],
      self.icons[:Stop],
      self.icons[:Next],
      self.icons[:Note],
      track_if_any
    ]
  end # }}}
end # }}}

on :mouse_down do |s, x, y, b| # {{{
  # Handle clicks based on x coord
  action = case x
    when  0..15 then :Previous
    when 16..31 then toggle_state
    when 32..47 then :Stop
    when 48..63 then :Next
  end

  send_action(action)

  update_status
end # }}}

# Other grabs {{{
{
  :SpotifyPlay => :Play,  :SpotifyPause    => :Pause,
  :SpotifyStop => :Stop,  :SpotifyPrevious => :Previous,
  :SpotifyNext => :Next
}.each do |k, v|
  grab k do |s|
    send_action(v)
  end
end # }}}
