#!/usr/bin/env python

"""

Gwibber Client
SegPhault (Ryan Paul) - 05/29/2007

"""

import sys, gtk, optparse, dbus, wnck, time
from os.path import join, dirname, exists, realpath, abspath
from dbus.mainloop.glib import DBusGMainLoop
from dbus import DBusException
import gettext
from gettext import lgettext as _
if hasattr(gettext, 'bind_textdomain_codeset'):
    gettext.bind_textdomain_codeset('gwibber','UTF-8')
gettext.textdomain('gwibber')

######################################################################
# Don't run again if we are already running
progname = "gwibber"
screen = wnck.screen_get_default()
while gtk.events_pending():
  gtk.main_iteration()
for w in screen.get_windows():
  if w.get_application().get_name() == progname:
    w.activate(int(time.time()))
    w.move_to_workspace(screen.get_active_workspace())
    quit()

######################################################################
# Setup path

LAUNCH_DIR = abspath(sys.path[0])
SOURCE_DIR = join(LAUNCH_DIR, "..", "gwibber")

DBusGMainLoop(set_as_default=True)

# If we were invoked from a Gwibber source directory add that as the
# preferred module path ...
if exists(join(SOURCE_DIR, "client.py")):
    sys.path.insert(0, realpath(dirname(SOURCE_DIR)))
    try:
      from gwibber.microblog.util import log
      log.logger.name = "Gwibber GNOME Client"
      log.logger.info("Running from the source tree")
      from gwibber import client
    finally:
        del sys.path[0]
else:
    from gwibber.microblog.util import log
    log.logger.name = "Gwibber GNOME Client"
    log.logger.info("Running from the system path")
    from gwibber import client

######################################################################
# Options 
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-d", "--debug", action="store_true",
                  dest="debug", default=False,  
                  help=_("Log debug messages"))
parser.add_option("-o", action="store_true",
                  dest="stdout", default=False,
                  help="Log to stdout")
(options, args) = parser.parse_args()

if options.debug:
  log.logger.setLevel(log.logging.DEBUG)
else:
  log.logger.setLevel(log.logging.INFO)
if options.stdout:
  # define a Handler which writes INFO messages or higher to the sys.stderr
  console = log.logging.StreamHandler()
  if options.debug:
    console.setLevel(log.logging.DEBUG)
  else:
    console.setLevel(log.logging.INFO)
  # set a format which is simpler for console use
  formatter = log.logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
  console.setFormatter(formatter)
  log.logger.addHandler(console)

######################################################################

client.Client()
gtk.main()
