# User defined functions

import time, string, sys

# Important: The functions behave more or less as if they were
# methods of irchandler.

# All functions defined in this global namespace will be viewed as
# commands for the bot, but only functions.

url_list = []

# An entry in URL-list has the format:
# (nick, url, reason, timestamp)
# Everything except timestamp are strings, timestamp is a number

# Level 0 commands

def PASS(mother, event):
	mother.throttler.queue('NOTICE', (event['prefix'][0],
		"Berre be om op direkte utan PASS eller passord. Denne boten bruker ikkje passord."))

def DATE(mother, event):
	mother.throttler.queue('NOTICE', (event['prefix'][0],
		time.strftime("%A, %Y-%m-%d %H:%M:%S, %V",
			time.localtime(time.time()))))

def HELP(mother, event):
	mother.throttler.queue('NOTICE', (event['prefix'][0],
		"http://sk.nvg.org/tut/botgreier"))


def REMIND(mother, event):
	# when no number, list known URLs
	params = string.split(event['params'][1])
	if len(params) > 2:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Syntaks: REMIND [number]"))
		return
	elif len(url_list) == 0:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Ikkje nokon URLar bufra."))
		return
	elif len(params) == 2:
		try:
			n = int(params[1])
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: REMIND [number]"))
			return
	else:
		n = 1
	if n > len(url_list):
		n = 1
	i = len(url_list) - n
	mother.throttler.queue('NOTICE', (mother.channel,
		"%s minner om %s -- %s, lagt inn av %s %s" %
		(event['prefix'][0],
		url_list[i][1],
		url_list[i][2],
		url_list[i][0],
		time.strftime("%Y-%m-%d %H:%M:%S",
		time.localtime(url_list[i][3])))))

def TAIL(mother, event):
	# default 5
	params = string.split(event['params'][1])
	if len(params) > 2:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Syntaks: TAIL [number]"))
		return
	elif len(url_list) == 0:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Ikkje nokon URLar bufra."))
		return
	elif len(params) == 2:
		try:
			n = int(params[1])
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: TAIL [number]"))
			return
	else:
		n = 5
	if n > len(url_list):
		n = len(url_list)
	for i in range(len(url_list)-1, len(url_list)-n-1, -1):
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"(%d) %s -- %s, lagt inn av %s %s" %
			(len(url_list)-i,
			url_list[i][1],
			url_list[i][2],
			url_list[i][0],
			time.strftime("%Y-%m-%d %H:%M:%S",
			time.localtime(url_list[i][3])))))

def DUMP(mother, event):
	params = string.split(event['params'][1], None, 2)
	if len(params) != 3:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Syntaks: DUMP <url> <description>"))
		return
	if len(url_list) > 50:
		for i in range(len(url_list)-51, -1, -1):
			if url_list[i][3] < time.time()-172800:
				del url_list[i]
	url_check = filter(lambda x, url=params[1]: url == x[1],
		url_list)
	if len(url_check) > 0:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"%s la ut den %s, indeks %d" %
			(url_check[0][0],
			time.strftime("%Y-%m-%d %H:%M:%S",
				time.localtime(url_check[0][3])),
			len(url_list)-url_list.index(url_check[0])
			)))
	else:
		url_list.append((event['prefix'][0],
			params[1],
			params[2],
			time.time()))
		mother.throttler.queue('NOTICE', (mother.channel,
			"<%s> %s -- %s" %
			(event['prefix'][0],
			params[1],
			params[2])))

# Level 10 commands

def TOPIC(mother, event):
	if mother.userlvl(event['prefix']) >= 10:
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			mother.topic))

def IDLE(mother, event):
	if mother.userlvl(event['prefix']) >= 10:
		params = string.split(event['params'][1])
		if len(params) != 2:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: IDLE <nick>"))
			return
		lastspoke = mother.idlelist.get(string.lower(params[1]), None)
		if lastspoke == None:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Har ikkje registrert aktivitet frå %s" % params[1]))
		else:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"%s prata sist %s" % (params[1],
				time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(lastspoke)))))

def CONVERT(mother, event):
	convtable = {
		'm': 1.0,
		'km': 1e3,
		'mm': 1e-3,
		'AU': 1.49498e11,
		'ft': 3.04800e-1,
		'LY': 9.4605e15,
		'mile': 1.60934e3,
		'naut_mil': 1.85200e3,
		'parsec': 3.0837e16,
		'pica': 4.21752e-3,
		'punkt': 3.51460e-4,
		'in': 2.54000e-2,
		'yard': 9.14400e-1,
		'furlong': 2.01168e2,

		'kg': 1.0,
		'lb': 4.53592e-1,
		'oz': 2.83495e-2,

		'C': (1., 273.15),
		'K': 1.0,
		'F': (5./9., 255.3722222222),
		'R': 5./9.,

		'l': 1e-3,
		'm3': 1.0, 
		'gal_UK': 4.54609e-3,
		'gal_US_liq': 3.78541e-3,
		'gal_US_sol': 4.40488e-3,
		'pint_UK': 5.68261e-4,
		'pint_US_liq': 4.73176e-4,
		'pint_US_sol': 5.50611e-4,
		'fl_oz_US': 2.95735e-5,
		'fl_oz_UK': 2.84131e-5,
		'ss': 1.47868e-5,
		'ts': 4.92892e-6,

		'm/s': 1.,
		'kph': 2.77778e-1,
		'knop': 5.14444e-1,
		'c': 2.99792e8,
		'mph': 4.47040e-1,
		'furlong/fortnight': 2.01168e2/(14.*3600.*24.),

		'J': 1.,
		'kJ': 1e3,
		'BTU': 1.05506e3,
		'CVh': 2.64778e6,
		'erg': 1e7,
		'eV': 1.60219e-19,
		'cal': 4.18680,
		'kcal': 4.18680e3,
		'kWh': 3.60000e6,
		'kilotonn': 4.20000e12,

		'W': 1.,
		'kW': 1e3,
		'BTU/s': 1.05506e3,
		'CV': 7.35500e2,
		'erg/s': 1e7,
		'hestekraft': 7.35499e2,
		'hestekraft_UK': 7.45700e2,
		'megaBTU/h': 2.93071e5,

		'Pa': 1.,
		'atm': 1.01325e5,
		'bar': 1e5,
		'mmHg': 1.33322e2,
		'psi': 6.89476e3,
		'torr': 1.33322e2
	}
	groups = (
		('m', 'mm', 'km', 'AU', 'ft', 'LY', 'mile', 'naut_mil',
			'parsec', 'pica',
			'punkt', 'in', 'yard', 'furlong'),
		('kg', 'lb', 'oz'),
		('K', 'C', 'F', 'R'),
		('l', 'm3', 'gal_UK', 'gal_US_liq', 'gal_US_sol', 'pint_UK',
			'pint_US_liq', 'pint_US_sol', 'fl_oz_US', 'fl_oz_UK', 'ss', 'ts'),
		('m/s', 'kph', 'knop', 'c', 'mph', 'furlong/fortnight'),
		('J', 'kJ', 'BTU', 'CVh', 'erg', 'eV', 'cal', 'kcal', 'kWh',
			'kilotonn'),
		('W', 'kW', 'BTU/s', 'CV', 'erg/s', 'hestekraft', 'hestekraft_UK',
			'megaBTU/h'),
		('Pa', 'atm', 'bar', 'mmHg', 'psi', 'torr')
	)

	def conv_error(mother, event):
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Syntaks: CONVERT <måltal> <eining>"))

	if mother.userlvl(event['prefix']) >= 10:
		params = string.split(event['params'][1])
		if len(params) != 3:
			conv_error(mother, event)
			return
		try:
			measure = float(params[1])
			unit = params[2]
			convertion = convtable[unit]
		except:
			conv_error(mother, event)
			return
		try:
			a, b = convertion
		except:
			a, b = convertion, 0.
		answer = []
		measure = measure * a + b
		for group in groups:
			if unit in group:
				unitgroup = group
				break
		for nom in unitgroup:
			try:
				a, b = convtable[nom]
			except:
				a, b = convtable[nom], 0.
			answer.append("%.5g %s" % ((measure-b)/a, nom))
		answer = string.join(answer, ', ')

		mother.throttler.queue('NOTICE', (event['prefix'][0],
			answer))

# Bull is of course short for bulletin. :)

def BULL(mother, event):
	if mother.userlvl(event['prefix']) >= 10:
		try:
			bull = mother.BULLETINS
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Ikkje nokon meldingar."))
			return
		if not len(bull):
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Ikkje nokon meldingar."))
		else:
			for bulletin in bull:
				mother.throttler.queue('NOTICE', (event['prefix'][0],
					bulletin))

def ADDBULL(mother, event):
	if mother.userlvl(event['prefix']) >= 10:
		try:
			bull = mother.BULLETINS
		except:
			mother.BULLETINS = []
			bull = mother.BULLETINS
		msg = string.split(event['params'][1], None, 1)
		if len(msg) != 2:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: ADDBULL <melding>"))
			return
		bull.append(string.strip(msg[-1]))
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Melding lagt inn."))

def MAIL(mother, event):
	def findnick(mother, nick):
		nick = string.upper(nick)
		for entry in mother.users:
			if nick == string.upper(entry[0]):
				return entry
		return None
	if mother.userlvl(event['prefix']) >= 10:
		msg = string.split(event['params'][1])
		if len(msg) != 2:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: MAIL <nick>"))
			return
		entry = findnick(mother, msg[1])
		if entry:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"E-mail: %s" % entry[3]))
		else:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"%s er eit uregistrert nick." % msg[1]))
	
# Level 20 commands

def OP(mother, event):
	if mother.userlvl(event['prefix']) >= 20:
		mother.throttler.queue('RAW', ("MODE %s +o %s"
			% (mother.channel, event['prefix'][0]),))


# Level 50 commands

def DELBULL(mother, event):
	if mother.userlvl(event['prefix']) >= 50:
		try:
			bull = mother.BULLETINS
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Ikkje nokon meldingar."))
			return
		msg = string.split(event['params'][1], None, 1)
		if len(msg) != 2:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Syntaks: DELBULL <n>"))
			return
		try:
			msgno = string.atoi(msg[1])
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"n må vera eit heiltal."))
			return
		try:
			del bull[msgno]
		except:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Ugyldig n."))
		else:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Melding nummer %s sletta." % msgno))

# Level 100 commands

def NEXTNICK(mother, event):
	if mother.userlvl(event['prefix']) >= 100:
		# The event is actually ignored, only passed along to make the
		# normal function happy
		mother.ERR_NICKNAMEINUSE(event)

# Level 200 commands

def RAW(mother, event):
	if mother.userlvl(event['prefix']) >= 200:
		tmp = string.split(event['params'][1], None, 1)
		if len(tmp) == 1:
			mother.throttler.queue('NOTICE', (event['prefix'][0],
				"Må ha minst éitt argument."))
		else:
			mother.throttler.queue('RAW', (tmp[-1],))

def RELOADUSERS(mother, event):
	if mother.userlvl(event['prefix']) >= 200:
		mother.readusers(mother.userlist)
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Brukarlista er oppdatert."))

def RELOADCOMMANDS(mother, event):
	if mother.userlvl(event['prefix']) >= 200:
		mother.setupcommands()
		mother.throttler.queue('NOTICE', (event['prefix'][0],
			"Kommandoane er oppdaterte."))

def SHUTDOWN(mother, event):
	if mother.userlvl(event['prefix']) >= 200:
		mother.log.pipe.close()
		sys.exit(0)
