__module_name__ = "VastorsQuiz"
__module_version__ = "0.1"
__module_description__ = "Quiz for XCHAT"

import xchat
import time
import string
import re

print "loaded %s" % __module_name__

nextquesthnd = None    # Handler für die Funktion nächste Frage
showscorehnd = None    # Handler für die Punkte zeige Routine
vokhnd = None 	       # Handler für die Tipp-Hilfe
scoreshnd = None       # Handler für die Punkte Funktion der User
questhnd = None	       # Handler für die Frage anzeige Funktion der User
helphnd = None         # Handler für die Hilfe anzeige Funktion der User
access_vok = True      # vok-Hilfe verfügbar?
access_scores = True   # Punkteanzeige verfügbar?
access_question = True # Frage darf angezeigt werden?
access_help = True     # Hilfe darf angezeigt werden?
startnum = 0           # Startnumer der Fragen

class question:
	text = []        # Fragen
	answer = []      # Antworten
	number = -1      # aktuelle Frage
	time = None      # Startzeit der Frage
	chan = '#mychan' # Aktueller Quiz-Channel
	active = False   # läuft das quiz?
	def loadfile(self, filename):
		quests = open(filename)
		record = quests.readline()
		record = quests.readline()
		record = quests.readline()
		while 1:
			self.text.append(quests.readline().rstrip('\r\n'))
			self.answer.append(quests.readline().rstrip('\r\n'))
			record = quests.readline()
			if record == "": break
	def next(self):
		global nextquesthnd
		global vokhnd
		global access_vok
		nextquesthnd = xchat.hook_timer(90000, next_question_timer, xchat.PRI_HIGHEST)
		vokhnd = xchat.hook_timer(30000, vok_timer)
		access_vok = False
		self.number += 1
		xchat.command("MSG %s \0033 Frage %s: %s" % (self.chan, str(self.number+1), self.text[self.number]) )
		self.time = time.time()
	def start(self, startnum):
		self.chan = xchat.get_info("channel")
		self.active = True
		if (len(self.text)<1):
			xchat.command("MSG %s Keine Fragen geladen!" % (self.chan))
		else:
			self.number = startnum
			self.next()
			install_timer()
        def timeElapsed(self):
                if self.time:
                        return time.time() - self.time
	def reset(self):
		self.number = -1
        def startnumber(self, num):
                self.number = int(num)
	def current_answer(self):
		if (self.number != -1): return self.answer[self.number]
		else: return ''
        def current_number(self):
                if (self.number != -1): return self.number
                else: return 0
	def current_question(self):
                xchat.command("MSG %s \0033 Frage %s: %s" % (self.chan, str(self.number+1), self.text[self.number]) )
	def quizchan(self):
		if (self.chan != ''): return self.chan
                else: return ''
	def isactive(self):
		if (self.active): return True
		else: return False

class highscore:
	points = {} # Punkteliste
	dummy = []  # temporär Array
	def add(self, nick):
		if self.points.has_key(nick):
                	self.points[nick] += 1
                else:
                	self.points[nick] = 1
		return self.points[nick]
	def show(self, userdata):
		global startnum
		if (los.isactive()):
			list = self.points.items()
                	self.dummy = []
                	for i in list:
                        	self.dummy.append((i[1], i[0]))
                	self.dummy.sort()
                	self.dummy.reverse()
			xchat.command("MSG %s \0033 Highscore nach %s Fragen:" % (los.quizchan(), str(los.current_number()-startnum)) )
                	rank = 0
                	for i in self.dummy:
                        	rank += 1
                        	xchat.command("MSG %s \0033 %s.: %s (%s points)" % (los.quizchan(), rank, i[1], str(i[0])))
                        	if rank >= 3:
                        		break;
		return 1



los = question()
hghscr = highscore()
los.loadfile('/home/vastor/FILES/download/xchat/Susus_Quizfragen.txt') # Standardfragen laden

def help_timer(userdata):
	global access_help
	access_help = True
	return 0

def quest_timer(userdata):
        global access_question
	access_question = True
        return 0

def scores_timer(userdata):
	global access_scores
        access_scores = True
        return 0

def vok_timer(userdata):
	global access_vok
	access_vok = True
	return 0

def next_question_timer(userdata):
        if (los.isactive()):
		xchat.command("MSG %s \0033 Antwort war: %s (aufgel??st nach %s sek)" % (los.quizchan(), los.current_answer(), str(round(los.timeElapsed(),1))) )
        	los.next()
	return 0

def install_timer():
	global showscorehnd
        showscorehnd = xchat.hook_timer(600000, hghscr.show)

def voktip():
	pattern = re.compile('[^aeiou* ]', re.IGNORECASE)
	return pattern.sub('.', los.current_answer())

def comp_answer(given_answer):
	pattern2 = re.compile(r'\*', re.IGNORECASE)
	tmp_answer = pattern2.sub(r'.{0,2}', los.current_answer())
	pattern = re.compile(tmp_answer, re.IGNORECASE)
	return pattern.search(given_answer)

def quiz(word, word_eol, userdata):
	aktchan = los.quizchan()
	if comp_answer(word_eol[1]) and xchat.get_info("channel") == aktchan:
        	if (nextquesthnd):
                	xchat.unhook(nextquesthnd)
		if (vokhnd):
			xchat.unhook(vokhnd)
		timeans = los.timeElapsed()
                playernick = word[0]
                xchat.command("MSG %s \0033 %s war die richtige Antwort" % (aktchan, los.current_answer()) )
                xchat.command("MSG %s \0033 gelöst nach %s sek." % (aktchan, str(round(timeans,1))) )
                xchat.command("MSG %s \0033 %s bekommt 1 Punkt (Gesamt %s)!" % (aktchan, playernick, str(hghscr.add(playernick))) )
		los.next()
msghook = xchat.hook_print("Channel Message",quiz)

def startquiz(word, word_eol, userdata):
	global startnum
	aktchan=los.quizchan()
	if word[1] == 'start':
                xchat.command("MSG %s \0033 %s (2004)" % (xchat.get_info("channel"), __module_name__) )
		if (nextquesthnd):
                        xchat.unhook(nextquesthnd)
                if (vokhnd):
                        xchat.unhook(vokhnd)
		if (len(word)>2):
			startnum = int(word[2])-2
			los.start(int(word[2])-2)
		else: los.start(-1)
        if word[1] == 'next':
                xchat.command("MSG %s \0033 Antwort war: %s (aufgelöst nach %s sek)" % (aktchan, los.current_answer(), str(round(los.timeElapsed(),1))) )
                if (nextquesthnd):
                        xchat.unhook(nextquesthnd)
                if (vokhnd):
                        xchat.unhook(vokhnd)
		los.next()
        if word[1] == 'reset':
                xchat.command("MSG %s \0033 Quiz wurde neu gestartet " % (aktchan) )
                if (nextquesthnd):
                        xchat.unhook(nextquesthnd)
                if (vokhnd):
                        xchat.unhook(vokhnd)
		los.reset()
		los.next()
	if word[1] == 'number':
                xchat.command("MSG %s \0033 Quiz startet mit Frage %s" % (aktchan, word[2]) )
                los.startnumber(int(word[2])-2)
                los.next()
	return xchat.EAT_ALL

def usercommands(word, word_eol, userdata):
        global access_help
	global access_vok
	global access_question
	global access_scores
	global scoreshnd
	global questhnd
	global helphnd
	aktchan=los.quizchan()
        if word_eol[1].count('!scores') and xchat.get_info("channel")==aktchan and los.isactive() and access_scores:
                hghscr.show(1)
		scoreshnd = xchat.hook_timer(180000, scores_timer)
		access_scores = False
        if word_eol[1].count('!vok') and xchat.get_info("channel")==aktchan and los.isactive() and access_vok:
                xchat.command("MSG %s \0033 Tipp: %s" % (aktchan, voktip()) )
        if word_eol[1].count('!question') and xchat.get_info("channel")==aktchan and los.isactive() and access_question:
                los.current_question()
		questhnd = xchat.hook_timer(30000, quest_timer)
		access_question = False
        if word_eol[1].count('!quizhelp') and xchat.get_info("channel")==aktchan and los.isactive() and access_help:
                xchat.command("MSG %s \0033 Verf??gbare Befehle:" % (aktchan) )
                xchat.command("MSG %s \0033 !scores    : zeigt die besten 3 (nur alle 3 min m??glich)" % (aktchan) )
                xchat.command("MSG %s \0033 !vok       : zeigt als Tipp die vokale an (erst nach 30 sek möglich)" % (aktchan) )
                xchat.command("MSG %s \0033 !question  : zeigt die Frage nochmal an (nur alle 30 sek möglich)" % (aktchan) )
                xchat.command("MSG %s \0033 !quizhelp  : zeigt diese Hilfe (nur alle 5 min m??glich)" % (aktchan) )
		helphnd = xchat.hook_timer(300000, help_timer)
		access_help = False
	return xchat.EAT_NONE

cmdhook = xchat.hook_command("QUIZ",startquiz,help="Usage: QUIZ <command>")
ucmdhook = xchat.hook_print("Channel Message", usercommands)

def catch_nick_change(word, word_eol, userdata):
        if hghscr.points.has_key(word[0]):
                oldnick = word[0]
                newnick = word[1]
                nickpoints = int(hghscr.points[oldnick])
                hghscr.points[newnick] = nickpoints
                hghscr.points.__delitem__(oldnick)
        return xchat.EAT_NONE
xchat.hook_print("Change Nick",catch_nick_change)


def unload(userdata):
	xchat.unhook(msghook)
	xchat.unhook(cmdhook)
	xchat.unhook(ucmdhook)
	if (nextquesthnd):
		xchat.unhook(nextquesthnd)
	if (showscorehnd):
		xchat.unhook(showscorehnd)
	if (vokhnd):
		xchat.unhook(vokhnd)
       	if (questhnd):
                xchat.unhook(questhnd)
        if (scoreshnd):
                xchat.unhook(scoreshnd)
        if (helphnd):
                xchat.unhook(helphnd)
	xchat.command("MSG %s \0033 Das Quiz wurde beendet." % (los.quizchan()) )
	print "Bye bye"

xchat.hook_unload(unload)