#!/usr/bin/python

import sys, os
from random import Random
from optparse import OptionParser
import re
from string import join
import locale

# default search path for mods
_mods_path = '/usr/share/games/fortune/'

# subroutines

def show_mods():
	mods = os.listdir(_mods_path)

	# remove dat file from list
	for name in mods:
		if name.find('.dat') > 0: 
			mods.remove(name)
	mods.sort()
	print("Mods available:\n%s\n" % (join(mods,', ')))

	return

def get_random_mod():
	mods = os.listdir(_mods_path)

	for name in mods:
		if name.find('.dat') > 0:
			mods.remove(name)
	mods.sort()
	n = 0
	n = get_mod_number(len(mods))

	return mods[n]


def print_citate(cit=None):
	if cit is None or cit == '':
		return None
	
	lang, charset = locale.getdefaultlocale()
	if charset != 'utf-8':
		print(unicode(cit,'utf-8').encode(charset))
	else:
		print(cit)

	return


def make_array(lines=None):
	if lines is None or lines == []:
		return None

	acc = []
	s = ''
	format = False
	while (lines[-1] == '\n'):
		lines.remove(lines[-1])
	for line in lines:
		if line != '%\n':
			s = s+line
		else:
			acc.append(s.rstrip('\n'))
			s=''
			format = True
	acc.append(s)

	if format:
		return acc
	else:
		return None


def show_one(mod=None):
	if mod is None or mod == '':
		return

	f = open(mod)
	array = make_array(f.readlines())
	f.close()
	if array is None:
		print("mod %s corrupted or not mod" % (mod))
		return

	n = 0
	r = Random()
	i = r.randint(0,20)
	for i in range(0,i):
		n = r.randint(0,len(array)-1)

	print_citate(array[n])

	return


def show_match(mod=None,pattern=None):
	if mod is None or mod == '':
		return
	if pattern is None or pattern == '':
		return

	count = 0
	f = open(mod)
	array  = make_array(f.readlines())
	f.close()
	if array is None:
		print("mod %s corrupted or not mod" % (mod))
		return

	first = True
	p = re.compile(pattern, re.S)
	for cit in array:
		m = re.search(p, cit)
		if m is not None:
			print_citate('%\n'+cit)
			count = count+1

	if count > 0: print("%")

	return count





def get_mod_number(max=None):
	if max is None or max == 0:
		return 0
	r = Random()
	n = 0
	for i in range(0,r.randint(0,9)):
		n = r.randint(0,max-1)

	return n


# ==========================================================
def main():
	usage = "usage: %prog [options] mod_name1 mod_name2"
	parser = OptionParser(usage=usage, version='%prog 0.1')

	parser.add_option("-m", "--match", action="store", type="string", dest="match",
			help="search in mod for match specified pattern")
	parser.add_option("-c", "--count", action="store_true", dest="count",
			help="count and show total citates from mod")
	parser.add_option("-f", "--files", action="store_true", dest="files",
			help="show all available mods in standard part (%s)" %(_mods_path))
	parser.add_option("-n", action="store", type="int", dest="length", default=160,
			help="Set the longest fortune length (in characters) considered to be ``short'' (the default is  160)")


	(options, args) = parser.parse_args()

	if args == []:
		if os.path.exists(_mods_path):
			mod = _mods_path + get_random_mod()
		else:
			print("No mods installed")
			return
	else:
		for mod in args:
			if not os.path.exists(_mods_path+mod) and not os.path.exists(mod):
				print("mod '%s' does not exist" % (mod))
				return

		if len(args) > 1:
			nm = get_mod_number(len(args))
			if args[nm].find(_mods_path) > 0:
				mod = args[nm]
			else:
				mod = _mods_path+args[nm]
		else:
			if args[0].find(_mods_path) > 0:
				mod = args[0]
			else:
				mod = _mods_path+args[0]


	if options.match:
		if options.count:
			print ("total: %d" % (show_match(mod,options.match)))
		else:
			show_match(mod,options.match)
		return

	if options.files:
		show_mods()
		return

	
	show_one(mod)

	return





if __name__ == '__main__':
	main()
