#!/usr/bin/env ruby
# encoding: utf-8

# Copyright Atlassian 2013

require 'dbus'

class MprisHipChatBridge

    MPRISIFACE = "org.mpris.MediaPlayer2."

    def initialize
        loop = DBus::Main.new
        bus = DBus::SessionBus.instance
        loop << bus
        possibleServices = []
        bus.proxy.ListNames[0].each{ |serviceName|
            possibleServices << serviceName if serviceName.start_with?(MPRISIFACE)
        }
        possibleServices.sort!

        if possibleServices.size < 1  then
            puts "No MPRIS 2 players are running. Try Amarok!"
            return
        elsif possibleServices.size > 1 then
            puts "Multiple players are running. Picking #{possibleServices.first.sub(MPRISIFACE, "").capitalize}."
        end

        amarokService = bus.service(possibleServices.first)
        player = amarokService.object("/org/mpris/MediaPlayer2")
        player.introspect

        hipchatService = bus.service("com.hipchat.Script1")
        @hipchat = hipchatService.object("/com/hipchat/Script1")

        @hipchat.introspect
        @hipchat.default_iface = "com.hipchat.Script1"

        updateHipchat(player["org.mpris.MediaPlayer2.Player"].all_properties)

        player["org.freedesktop.DBus.Properties"].on_signal(bus, "PropertiesChanged") do |iface,updated,invalid|
            if iface == "org.mpris.MediaPlayer2.Player" then
                updateHipchat(updated)
            end
        end
        
        begin
            loop.run
        rescue SystemExit, Interrupt
            clearStatus
        end   
    end

    def updateHipchat(updated)
        data = updated["Metadata"]
        status = updated["PlaybackStatus"]
        if status == "Playing" and data and data.count > 2 then 
            title = data['xesam:title']
            artist = data['xesam:artist'][0] == "Various Artists" ? false : data['xesam:artist'][0]
            if title and artist
                status = "♬ #{artist} - #{title} ♫♪"
                @hipchat["com.hipchat.Script1"].SetStatus(status)
            elsif title
                @hipchat.SetStatus("♬ #{title} ♫")
            else
                @hipchat.SetStatus("")
            end
        elsif status == "Paused" or status == "Stopped"
            clearStatus
        end
    end

    def clearStatus
        @hipchat.SetStatus("")
    end

end

MprisHipChatBridge.new