#!/usr/bin/python

# This is a part of the third-party applets for Cairo-Dock
#
# Copyright : (C) 2010 by Fabounet
# E-mail : fabounet@users.berlios.de
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# http://www.gnu.org/licenses/licenses.html#GPL

####################
### dependancies ###
####################
import sys
import os.path
import subprocess
import ConfigParser
import gobject
import glib
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gettext

#gettext.install('cd-xchat', '/usr/share/locale')
gettext.bindtextdomain('cd-xchat', '/usr/share/locale')
gettext.bind_textdomain_codeset ('cd-xchat', 'UTF-8');
gettext.textdomain('cd-xchat')

applet_name = os.path.basename(os.path.abspath("."))  # the name of the applet must the same as the folder.
DBusGMainLoop(set_as_default=True)

##################################
### callbacks on the main icon ###
##################################
def _try_connect():
	myApplet.connect_to_xchat()
	if myApplet.xchat == None:  # toujours pas connecte.
		myApplet.iNbTries += 1
		if myApplet.iNbTries == 5:  # au bout de 5 essais on abandonne.
			myApplet.icon.ShowDialog("Couldn't connect to xchat :-(",4)
			myApplet.iSidConnect = 0
			return False
		return True
	else:  # connexion etablie.
		myApplet.iSidConnect = 0
		return False
def action_on_click(iState):
	if myApplet.xchat == None:  # pas connecte
		if myApplet.iSidConnect == 0:  # et pas en train de le faire
			try:
				subprocess.Popen(myApplet.cClass)
			except OSError:
				myApplet.icon.ShowDialog("Couldn't launch "+myApplet.cClass,5)
				return
			myApplet.iNbTries = 0
			myApplet.iSidConnect = gobject.timeout_add(1000,_try_connect)
		else:  # en cours de connexion
			myApplet.icon.ShowDialog("Connecting to xchat, please wait ...",4)
	else:  # on montre la fenetre.
		if myApplet.bHasFocus:  # la fenetre existe et a le focus.
			myApplet.icon.ShowAppli(False)  # on minimise la fenetre.
		else:  # soit la fenetre n'existe pas, soit elle n'a pas le focus.
			try:
				myApplet.xchat.Command("GUI SHOW")  # on n'utilise pas ShowAppli pour pouvoir detecter si xchat a quitte inopinement. En effet il ne nous notifie pas lorsqu'il s'arrete.
			except dbus.DBusException:  # cas ou xchat a quitte sans nous le dire.
				print "xhat has quitted without telling us !"
				myApplet.xchat = None
				myApplet.connect_to_xchat()
				if myApplet.xchat == None:  # pas sur le bus, il y'a de fortes chances qu'il ne soit pas lance.
					print "seems xchat is not running"
					subprocess.Popen("xchat")
					myApplet.iNbTries = 0
					myApplet.iSidConnect = gobject.timeout_add(1000,_try_connect)
				else:
					myApplet.xchat.Command("GUI SHOW")

def action_on_middle_click():
	if myApplet.xchat == None:
		return	
	ctx = myApplet.xchat.FindContext ('', '')  # NULL,NULL => the currently focused tab/window will be returned.
	myApplet.xchat.SetContext(ctx)  # on se place sur le canal courant dans la fenetre.
	myApplet.icon.AskText("Send a message on "+myApplet.xchat.GetInfo("channel"), "");

def action_on_build_menu():
	if myApplet.xchat == None:
		return
	chans = myApplet.list_channels()
	items=[]
	i=0
	for c in chans:
		items.append({"label": c, "id" : i})
		i += 1
	myApplet.icon.AddMenuItems(items)

def action_on_menu_select(iNumEntry):
	chans = myApplet.list_channels()
	print ">>> channel" + chans[iNumEntry]
	channel=''
	channel=chans[iNumEntry]
	ctx = myApplet.xchat.FindContext('', channel)
	if ctx == 0:
		return
	myApplet.xchat.SetContext(ctx)
	myApplet.xchat.Command("GUI FOCUS")  # pour donner le focus a l'onglet correspondant a notre contexte.

def action_on_scroll(bDirectionUp):
	print ">>> scroll",bDirectionUp,myApplet.iNbMsg
	if myApplet.iNbMsg != 0 :
		if bDirectionUp:
			myApplet.iCurrentMsg += 1
		else:
			myApplet.iCurrentMsg -= 1
		if myApplet.iCurrentMsg >= myApplet.iNbMsg:
			myApplet.iCurrentMsg = myApplet.iNbMsg - 1
		elif myApplet.iCurrentMsg < -1:
			myApplet.iCurrentMsg = -1
		if myApplet.iCurrentMsg >= 0:
			myApplet.icon.ShowDialog(myApplet.pMsgList[myApplet.iCurrentMsg], 10)
	
def action_on_answer(answer):
	print ">>> answer :",answer
	if answer == None or answer == '':
		return
	myApplet.xchat.Command("say "+answer);

def action_on_change_focus(has_focus):
	myApplet.bHasFocus = has_focus
	if has_focus:
		print ">>> got focus"
		if myApplet.iNbUnread > 0 and myApplet.config['msg animation'] != '':
			myApplet.icon.Animate('',0)
		myApplet.set_nb_unread_msg(0)
		myApplet.iCurrentMsg = -1

###############################
### callbacks on the applet ###
###############################
def action_on_stop():
	print ">>> our module is stopped"
	myApplet.end()
	loop.quit()

def action_on_reload(bConfigHasChanged):
	print ">>> our module is reloaded"
	if bConfigHasChanged:
		print ">>>  and our config has changed"
		myApplet.get_config()

#########################
### Events from xchat ###
#########################
def action_on_command_catched(words, words_eol, hook_id, ctx_id):
	if myApplet.HookCmdId != hook_id:
		return
	print ">>> CMD :" + words_eol[1]
	myApplet.icon.ShowDialog("Yes, Master ?",4)

def action_on_server_event(words, words_eol, hook_id, ctx_id):
	if myApplet.HookServerId != hook_id:
		return
	msg = words_eol[1]
	print ">>> EVENT :" + msg
	if myApplet.config['channel message']:
		myApplet.icon.ShowDialog(msg,max(1,len(msg)/myApplet.config['duration']))
	if myApplet.config['msg animation'] != '':
		myApplet.icon.Animate(myApplet.config['msg animation'],10)

def action_on_print_event(words, hook_id, ctx_id):
	if myApplet.HookPrintId != hook_id:
		return
	if len(words) < 2:
		return
	msg = words[1]
	print ">>> PRINT :" + msg
	if not myApplet.bHasFocus:  # si l'utilisateur n'est pas devant xchat, on le notifie du message.
		if myApplet.config['channel message']:
			if myApplet.iCurrentMsg != -1:
				msg = myApplet.pMsgList[myApplet.iCurrentMsg]+"\n------------------------------------------\n"+msg
			myApplet.icon.ShowDialog(msg,max(2,len(msg)/myApplet.config['duration']))
		if myApplet.config['msg animation'] != '':
			myApplet.icon.Animate(myApplet.config['msg animation'],10000)
		myApplet.set_nb_unread_msg(myApplet.iNbUnread+1)
	
	if myApplet.config['history'] != 0:  # on insere le message dans l'historique.
		myApplet.pMsgList.insert(0,words[1])
		myApplet.iNbMsg += 1
		if myApplet.iNbMsg > myApplet.config['history'] :
			del myApplet.pMsgList[myApplet.config['history']]
			myApplet.iNbMsg -= 1
		if myApplet.iCurrentMsg != -1:
			myApplet.iCurrentMsg = min(myApplet.iNbMsg-1, myApplet.iCurrentMsg+1)  # on l'insere au debut donc ca decale le message courant.
	
def action_on_unload_event():  # ne semble pas appele lorsque xchat quitte :-(
	print ">>> xchat quits"
	del myApplet.xchat
	myApplet.xchat = None
	del myApplet.pMsgList
	myApplet.pMsgList = None
	myApplet.iNbMsg = 0
	myApplet.iCurrentMsg = -1
	myApplet.set_nb_unread_msg(0)

####################
### Applet class ###
####################
class Applet:
	def __init__(self):
		self.icon = None
		self.config = {}
		self.cConfFile = os.path.expanduser("~/.config/cairo-dock/current_theme/plug-ins/"+applet_name+"/"+applet_name+".conf")  # path to the conf file of our applet.
		self.xchat = None
		self.HookServerId = 0
		self.HookCmdId = 0
		self.HookPrintId = 0
		self.iSidConnect = 0
		self.iNbTries = 0
		self.iNbMsg = 0
		self.pMsgList = []
		self.iCurrentMsg = -1
		self.iNbUnread = 0
		self.bHasFocus = False
		self.cClass = ''
	
	def get_config(self):
		keyfile = ConfigParser.RawConfigParser()
		keyfile.read(self.cConfFile)
		self.config['channel message'] = keyfile.getboolean('Configuration', 'channel message')
		self.config['msg animation'] = keyfile.get('Configuration', 'msg animation')
		duration = keyfile.getint('Configuration', 'duration')
		if duration == 0:
			self.config['duration'] = 16
		elif duration == 1:
			self.config['duration'] = 8
		else:
			self.config['duration'] = 4
		self.config['history'] = keyfile.getint('Configuration', 'history')
	
	def begin(self):
		self.connect_to_dock()
		self.connect_to_xchat()
		path = os.popen("which xchat-gnome").read().rstrip()
		print ">>> path to xchat-gnome : "+path
		if path == '':
			self.cClass = 'xchat'
		else:
			self.cClass = 'xchat-gnome'
		print ">>> class of the appli : "+self.cClass
		self.icon.ControlAppli(self.cClass)
	
	def end(self):
		self.disconnect_from_xchat()
	
	def connect_to_dock(self):
		# get our applet on the bus.
		applet_path = "/org/cairodock/CairoDock/"+applet_name  # path where our object is stored on the bus.
		bus = dbus.SessionBus()
		applet_object = bus.get_object("org.cairodock.CairoDock", applet_path)
		self.icon = dbus.Interface(applet_object, "org.cairodock.CairoDock.applet")  # this object represents our applet and also our icon inside the dock or a desklet.
		# connect to signals.
		self.icon.connect_to_signal("on_click", action_on_click)  # when the user left-clicks on our icon.
		self.icon.connect_to_signal("on_middle_click", action_on_middle_click)  # when the user middle-clicks on our icon.
		self.icon.connect_to_signal("on_build_menu", action_on_build_menu)  # when the user right-clicks on our applet (which builds the menu)
		self.icon.connect_to_signal("on_menu_select", action_on_menu_select)  # when the user selects an entry of this menu.
		self.icon.connect_to_signal("on_scroll", action_on_scroll)  # when the user scroll up or down on our icon.
		self.icon.connect_to_signal("on_answer", action_on_answer)  # when the user answer a question.
		self.icon.connect_to_signal("on_change_focus", action_on_change_focus)  # when the user (un)focuses the xchat window.
		self.icon.connect_to_signal("on_stop_module", action_on_stop)  # when the user deactivate our applet (or the DBus plug-in, or when the Cairo-Dock is stopped).
		self.icon.connect_to_signal("on_reload_module", action_on_reload)  # when the user changes something in our config, or when the desklet is resized (with no change in the config).
	
	def connect_to_xchat(self):
		# register a new plug-in in xchat.
		bus = dbus.SessionBus()
		print ">> connecting to xchat..."
		try:
			proxy = bus.get_object('org.xchat.service', '/org/xchat/Remote')
		except dbus.DBusException:
			print ">>> xchat not available on the bus"
			return
		remote = dbus.Interface(proxy, 'org.xchat.connection')
		path = remote.Connect ("xchat",
			"Cairo-Dock applet",
			"Cairo-Dock applet",
			"1.0")
		print ">>> path :" + path
		# get the plug-in on the bus.
		proxy = bus.get_object('org.xchat.service', path)
		self.xchat = dbus.Interface(proxy, 'org.xchat.plugin')
		print ">>> connected to " + self.xchat.GetInfo("network") + " (" + self.xchat.GetInfo("server") + ") as " + self.xchat.GetInfo("nick")
		# connect to signals.
		#self.HookServerId = self.xchat.HookServer('PART', 0, 0)  # 0 <=> normal priority, 0 <=> let it pass (PRIVMSG, NOTICE, PART, etc)
		self.HookCmdId = self.xchat.HookCommand("cairo-dock", 0, "pouic pouic", 0)  # 0 <=> normal priority, 0 <=> let it pass
		self.HookPrintId = self.xchat.HookPrint("Channel Message", 0, 0)  # 0 <=> normal priority, 0 <=> let it pass
		self.xchat.connect_to_signal("ServerSignal", action_on_server_event)
		self.xchat.connect_to_signal("CommandSignal", action_on_command_catched)
		self.xchat.connect_to_signal("PrintSignal", action_on_print_event)
		self.xchat.connect_to_signal("UnloadSignal", action_on_unload_event)
	
	def disconnect_from_xchat(self):
		if self.xchat == None:
				return
		if self.HookServerId != 0:
			self.xchat.Unhook(self.HookServerId)
			self.HookServerId = 0
		if self.HookCmdId != 0:
			self.xchat.Unhook(self.HookCmdId)
			self.HookCmdId = 0
		if self.HookPrintId != 0:
			self.xchat.Unhook(self.HookPrintId)
			self.HookPrintId = 0
		self.xchat.Disconnect()  # n'a pas l'air de marcher...
	
	def list_channels(self):
		chans=[]
		channels = self.xchat.ListGet ("channels")
		while self.xchat.ListNext (channels):
			name = self.xchat.ListStr (channels, "channel")
			chans.append(name)
		self.xchat.ListFree (channels)
		return chans
	
	def set_nb_unread_msg(self,n):
		myApplet.iNbUnread = n
		if n > 0:
			myApplet.icon.SetQuickInfo(format(n,"d"))
		else:
			myApplet.icon.SetQuickInfo('')
	
	#~ def list_channels_and_users(self):
		#~ channels = self.xchat.ListGet ("channels")
		#~ while self.xchat.ListNext (channels):
			#~ name = self.xchat.ListStr (channels, "channel")
			#~ print "------- " + name + " -------"
			#~ self.xchat.SetContext (xchat.ListInt (channels, "context"))
			#~ users = self.xchat.ListGet ("users")
			#~ while xchat.ListNext (users):
				#~ print "   Nick: " + self.xchat.ListStr (users, "nick")
			#~ self.xchat.ListFree (users)
		#~ self.xchat.ListFree (channels)

############
### main ###
############
if __name__ == '__main__':
	myApplet = Applet()
	myApplet.get_config()
	myApplet.begin()
	loop = gobject.MainLoop()
	loop.run()
	print ">>> bye"
	sys.exit(0)
