'''Decoder module for xChat.

Decodes non-ascii ISO8859-1 chars encoded in UTF8 sent by others into cp1251:
  No more accented crap instead of damn cyrillic! ;)

Feel free to tweak it any way you like.'''

__module_name__ = 'xcp_recoder'
__module_version__ = '0.2'
__module_description__ = 'Decodes non-ascii ISO8859-1 chars encoded in UTF8 sent by others into cp1251'
__module_author__ = 'Gustavo Niemeyer <gustavo@niemeyer.net>, Mike Kazantsev <mk.fraggod@gmail.com>'

import xchat

def recode(word, word_eol, userdata):
	event, pos = userdata
	if type(pos) is int:
		pos = (pos,)
	changed = False
	for i in pos:
		try:
			reencoded = word[i].decode('utf8').encode('ISO8859-1').decode('cp1251').encode('utf-8')
		except (UnicodeError, IndexError):
			continue
		if reencoded != word[i]:
			word[i] = reencoded
			changed = True
	if changed:
		xchat.emit_print(event, *word)
		return xchat.EAT_XCHAT
	else:
		return xchat.EAT_NONE

EVENTS = [
  ('Channel Action', 1),
  ('Channel Action Hilight', 1),
  ('Channel Message', 1),
  ('Channel Msg Hilight', 1),
  ('Channel Notice', 2),
  ('Generic Message', (0, 1)),
  ('Kick', 3),
  ('Killed', 1),
  ('Motd', 0),
  ('Notice', 1),
  ('Part with Reason', 3),
  ('Private Message', 1),
  ('Private Message to Dialog', 1),
  ('Quit', 1),
  ('Receive Wallops', 1),
  ('Server Notice', 0),
  ('Server Text', 0),
  ('Topic', 1),
  ('Topic Change', 1),
]

for event in EVENTS:
	xchat.hook_print(event[0], recode, event)

print 'xcp_recoder initiated'
