#!/usr/bin/python

# (c) David Hugh-Jones 2004
# hughjonesd@yahoo.co.uk


# this doesn't work for Red Hat
# import pygtk 
# pygtk.require('2.0')

import gtk
import gnome.applet
import gnome
import sys
import getopt
import threading
from blogfish import blogfish_functions
from blogfish.Ocean import Ocean



def usage():
	print """
		Usage:

		blogfish.py [options]

		Options:
		  -w            , --window              show in main window
		  -p <N>        , --port <N>            listen on port NN
		  -p PASV       , --port PASV           use passive server
		  -d            , --debug               send debug messages
		  -h <HOST>     , --host <HOST>         connect to HOST

	"""

def destroy_applet(applet, ocean):
	blogfish_functions.debug("Applet destroyed: quitting")
	ocean.quit()
	gtk.main_quit()	
	for thr in threading.enumerate():
		if thr is not threading.currentThread(): thr.join()
	sys.exit(0)
	
def sample_factory(applet, iid):
	global Host
	gtk.threads_init()
	ocean = Ocean(applet, Host)
	applet.connect("destroy", destroy_applet, ocean)
	ocean.run()
	return gtk.TRUE
	

try:
	opts, args = getopt.getopt(sys.argv[1:], \
			"dwp:h:", ["debug", "window", "port=", "host=", \
			"oaf-activate-iid=", "oaf-ior-fd="])
 	opts = dict(opts)
except:
	if "--oaf-activate-iid" in sys.argv:
		d = gtk.Dialog("Couldn't start applet!")
		d.vbox.add(gtk.Label(repr(sys.exc_info())))
		d.run()
	else:
		usage()
	sys.exit()
	
if "-p" in opts:
	blogfish_functions.Port = opts["-p"]
if "--port" in opts:
	blogfish_functions.Port = opts["--port"]
Host = None
if "-h" in opts: Host = opts["-h"]
if "--host" in opts: Host = opts["--host"]

if "-d" in opts or "--debug" in opts: 
	blogfish_functions.Debug = 1
	blogfish_functions.debug("Debugging output is turned on")
if "-w" in opts or "--window" in opts:
	mw = gtk.Window(gtk.WINDOW_TOPLEVEL)
	mw.set_title("applet")
	mw.connect("destroy", gtk.main_quit)
	gnome.init("blogfish", "1.0")
	app = gnome.applet.Applet()
	sample_factory(app, None)
	app.reparent(mw)
	mw.show_all()
	gtk.main()
	sys.exit()
else: 
	blogfish_functions.debug("starting up in panel applet mode")
	gnome.applet.bonobo_factory("OAFIID:GNOME_BlogfishAppletSample_Factory",  \
			gnome.applet.Applet.__gtype__, \
			"Blogfish", "0", sample_factory)

