import sys
import bonobo
from optparse import OptionParser

try:
    import dbus
except ImportError:
    HAVE_DBUS = False
else:
    HAVE_DBUS = True

def main():
    parser = OptionParser(usage="usage: %prog [options] [message]")
    parser.add_option("-f", "--full",
                      help="Message is in full format specification",
                      action="store_true", dest="full", default=False)
    parser.add_option("-s", "--stdin",
                      help="Read message from stdin;  Implies --full",
                      action="store_true", dest="stdin", default=False)
    if HAVE_DBUS:
        parser.add_option("", "--dbus",
                          help="Prefer D-BUS as IPC method",
                          action="store_true", dest="dbus", default=False)
    
    (options, args) = parser.parse_args()
    timeout = -1
    if len(args) == 2:
        print >> sys.stderr, "Warning: timeout argument is deprecated and will be removed in the future"
        timeout = int(args[1])
    if not options.stdin and not (1 <= len(args) <= 2):
        parser.error("wrong number of arguments")

    if options.stdin:
        msg = sys.stdin.read()
    else:
        msg = args[0]

    class ServerError(Exception):
        def __init__(self, value):
            self.value = value

    def send_dbus():
        osd = dbus.SessionBus().get_object("pt.inescporto.telecom.GnomeOSD", "/Server")
        if options.full or options.stdin:
            error = osd.showMessageFull(msg, dbus_interface="pt.inescporto.telecom.GnomeOSD")
        else:
            error = osd.showMessage(msg, timeout, dbus_interface="pt.inescporto.telecom.GnomeOSD")
        if error:
            raise ServerError(error)

    def send_bonobo():
        osd = bonobo.get_object("OAFIID:GNOME_OSD", "IDL:Bonobo/Application:1.0")
        osd.ref() # AppClient steals one reference
        osd = bonobo.AppClient(osd)

        if options.full or options.stdin:
            error = osd.msg_send("show-full", [msg])
        else:
            error = osd.msg_send("show", [msg, timeout])
        if error:
            raise ServerError(error)

    if HAVE_DBUS and options.dbus:
        order = [("D-BUS", send_dbus), ("Bonobo", send_bonobo)]
    else:
        order = [("Bonobo", send_bonobo)]
        if HAVE_DBUS:
            order.append(("D-BUS", send_dbus))

    for i, (name, func) in enumerate(order):
        if i > 0:
            print "Trying %s" % name
        try:
            func()
            break
        except ServerError, ex:
            print >> sys.stderr, "ServerError: %s" % ex.value
            raise SystemExit, 2
        except Exception, ex:
            print >> sys.stderr, "Error: %s" % ex
            continue
