# lamechan.py - xchat python script which converts utf-8 to iso-8859-15
# Copyright (C) 2005  M. Neumann
# Copyright (C) 2006  Tommi Saviranta
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

import xchat

__module_name__ = "lamechan"
__module_version__ = "fnord3-wnd1"
__module_description__ = "converts utf-8 back to iso-8859-15 in specified (lame) channels"


# change this if you want to use a different target charset
sourceCharset = 'utf-8'
targetCharset = 'iso-8859-15'
commonNetwork = 'common'

recursiveCall = False


# this functions checks if the current channel is in the lamechannels-list
def lameChannel():
  lame = False
  curnetwork = xchat.get_info("network")
  if curnetwork == None:
    curnetwork = commonNetwork
  curchannel = xchat.get_info("channel")
  for pair in lamechannels:
    if pair == [curnetwork, curchannel]:
      lame = True
  return lame


# this function reencodes the data
def recodeUTF(command, data):
  try:
    xchat.command(command + " " + data.decode(sourceCharset).encode(targetCharset))
  except:
    xchat.command("echo lamechan: unable to handle \"" + data + "\"")
    return False
  return True


# encoding of messages takes place in this function
def sendmessage_cb(word, word_eol, userdata):
  global recursiveCall
  if recursiveCall == True:
    recursiveCall = False
    return xchat.EAT_NONE
 
  if lameChannel() == False:
    return xchat.EAT_NONE

  recursiveCall = True
  if recodeUTF("say",word_eol[0]) == False:
    recursiveCall = False
    return xchat.EAT_NONE
  return xchat.EAT_ALL


# callback for the action-command
def action_cb(word, word_eol, userdata):
  global recursiveCall
  if recursiveCall == True:
    recursiveCall = False
    return xchat.EAT_NONE

  if lameChannel() == False:
    return xchat.EAT_NONE

  recursiveCall = True
  if recodeUTF("me",word_eol[1]) == False:
    recursiveCall = False
    return xchat.EAT_NONE
  return xchat.EAT_ALL


# callback for the topic-command
def topic_cb(word, word_eol, userdata):
  global recursiveCall
  if recursiveCall == True:
    recursiveCall = False
    return xchat.EAT_NONE

  if lameChannel() == False:
    return xchat.EAT_NONE

  recursiveCall = True
  if recodeUTF("topic",word_eol[1]) == False:
    recursiveCall = False
    return xchat.EAT_NONE
  return xchat.EAT_ALL


# callback for the /lamechan command
def lamechan_cb(word, word_eol, userdata):
  network = xchat.get_info("network")
  channel = xchat.get_info("channel")
  if channel == None:
    print "lamechan error: channel == None"
    return xchat.EAT_ALL
  if network == None:
    print "lamechan notification: network == None"
    network = commonNetwork
    # return xchat.EAT_ALL

  if len(word) == 1:
    for pair in lamechannels:
      if pair == [network, channel]:
        print "this channel is lame"
	return xchat.EAT_ALL
    print "this channel is not lame"

  elif len(word) == 2:
    if word[1] == "on":
      for pair in lamechannels:
        if pair == [network, channel]:
	  print "channel is already a lame channel"
	  return xchat.EAT_ALL
      lamechannels.append([network, channel])
      print "added " + channel + "@" + network + " to the lamechannels list"
    elif word[1] == "off":
      try:
        lamechannels.remove([network, channel])
        print "removed " + channel + "@" + network + " from the lamechannels list"
      except ValueError:
        print "channel was no lame channel"
    elif word[1] == "list":
      if len(lamechannels) > 0:
        print "lame channels:"
        for pair in lamechannels:
	  print pair[1] + "@" + pair[0]
      else:
        print "no lame channels in list"
    else:
      print "unknown option: " + word[1]

  return xchat.EAT_ALL


# called when the script is unloaded (either manually or when closing xchat-2)
def unload_cb(userdata):
  try:
    chanfile = open(xchat.get_info("xchatdir") + "/lamechannels", "w")
    if len(lamechannels) == 0:
      chanfile.close()
      return
    first = True
    for pair in lamechannels:
      if first:
        chanfile.write(pair[0] + " " + pair[1])
	first = False
      else:
        chanfile.write("\n" + pair[0] + " " + pair[1])
    chanfile.close()
  except IOError:
    print "lamechan error: can't write chanfile"


# reading lamechannel-list
lamechannels = []
try:
  chanfile = open(xchat.get_info("xchatdir") + "/lamechannels", "r")
  templist = chanfile.read().split("\n")
  chanfile.close()
  if not templist == ['']:
    for channel in templist:
      lamechannels.append(channel.split(" "))
  del chanfile
  del templist
except IOError:
  print "lamechan warning: can't read chanfile"


# hooking the commands
xchat.hook_command("", sendmessage_cb)
xchat.hook_command("me", action_cb)
xchat.hook_command("topic", topic_cb)
xchat.hook_command("lamechan", lamechan_cb, help="/LAMECHAN {on|off|list}")
xchat.hook_unload(unload_cb)

print "lamechan loaded successfully"
