#!/usr/bin/python
# -*- coding: utf-8 -*-
import pyplwn, random, pickle, os, os.path, generators, wordsutils
from generators.HWBST import HWBSTGenerator
from generators.EWBST import EWBSTGenerator
from generators.lazyEWBST import LazyEWBSTGenerator 
	
def main(wordsfile, udictfile, outdir, test_name, threshold = 1000, flex = 'subst', no_of_detractors = 3, test_type = 'HWBST', user = 'wordnet', passwd = 'wordnet',
		host = 'localhost', db ='wordnet', port = 3306, seed = None, rowsdir=''):
	
	import codecs
	random.seed(seed)

	print "WBST generator... \nInitalizing database..."

	db = pyplwn.database.Database(user = user, passwd = passwd, host = host, db = db, port = port, encoding = "utf8")
	db.set_pos_filter([pyplwn.database.DBEnums.get_pos(flex)])

	all_words = wordsutils.load_words(wordsfile)
	detractors = wordsutils.load_words(udictfile)
	print "Before filtering:", len(all_words)
	all_words = wordsutils.wordnet_filter( all_words, db )
	print "After filtering:", len(all_words)
	#udict = load_udict(udictfile, flexset) #flexset i.e. set(['subst']) 
	#frequent,infrequent = filter_words(all_words, threshold, udict)
	
	if test_type == 'EWBST':
		wn = pyplwn.wngraph.WNGraph( [db.Relations.get_relation_by_name("hiperonimia"), db.Relations.get_relation_by_name("hiponimia")], db, False )
		testgen = EWBSTGenerator(db, wn, all_words, all_words , no_of_detractors )
		test = testgen.generate()
		wordsutils.save_questions(test, outdir + test_name + ".csv")
		
	elif test_type == 'lazyEWBST':
		wn = pyplwn.wngraph.WNGraph( [db.Relations.get_relation_by_name("hiperonimia"), db.Relations.get_relation_by_name("hiponimia")], db, False )
		testgen = LazyEWBSTGenerator(db, wn, rowsdir + 'words', rowsdir, all_words, all_words, no_of_detractors)
		test = testgen.generate()
		wordsutils.save_questions(test, outdir + test_name + ".csv")
		
	elif test_type == 'HWBST':
		testgen = HWBSTGenerator(db, all_words, detractors , no_of_detractors, True)
		test = testgen.generate()
		wordsutils.save_questions(test, outdir + test_name + ".csv")
		
	elif test_type == 'WBST':
		testgen = HWBSTGenerator(db, all_words, all_words , no_of_detractors, False)
		test = testgen.generate()
		wordsutils.save_questions(test, outdir + test_name + ".csv")
	else:
		raise Exception('Wrong test type')
	
if __name__ == "__main__":
	import sys, argparse
	parser = argparse.ArgumentParser(description='WBST generator')
	#positional arguments
	parser.add_argument('words_file',  action='store', 
		help='Path to the file with words for questions')
	parser.add_argument('dict_file',  action='store', 
		help='Path to the file with dictionary')
	parser.add_argument('out_dir',  action='store', 
		help='Path to the output directory')
	parser.add_argument('test_name',  action='store', 
		help='Filename of generated test (without extension)')
	
	#optional arguments
	parser.add_argument('--test_type', action='store', dest='test', default='HWBST', 
		help='Type of the test {HWBST, WBST, EWBST, lazyEWBST}  (default=HWBST)')
	parser.add_argument('-s',action='store', dest='seed', default=None,
		help='Value of seed for random (default=None)')
	parser.add_argument('-D',action='store', dest='detractors', default=3,
		help='Number of detractors (default=3)')
	parser.add_argument('-t', action='store', dest='threshold', default=1000,
		help='Term frequency threshold (default=1000)')
	parser.add_argument('-f', action='store', 
		dest='flex', default='subst',
		help='Type of flex (default=\'subst\')')
	
	#lazyEWBST arguments
	lazy = parser.add_argument_group('lazyEWBST arguments')
	lazy.add_argument('--lazy_rows',action='store', dest='rows', 
		help='Required! Directory with generated matrices')
	lazy.add_argument('--close_path', action='store', dest='number', default=4, 
		help='Longest path between question (or answer) and detractor (default=4)')
	
	#database arguments
	database = parser.add_argument_group('Database arguments')
	database.add_argument("-u", action='store', dest="user", default = 'wordnet', help="Database user")
	database.add_argument("-H", action='store', dest="host", default = 'localhost', help="Database host")
	database.add_argument("-p", action='store', dest="passwd", default = 'mylocaldbpasswd', help="Database password")
	database.add_argument("-d", action='store', dest="db", default = 'wordnet4', help="Database schema")
	database.add_argument("-P", action='store', dest="port", default = 3306, help="Database port")
	
	args = parser.parse_args()
	
	if not os.path.isfile(args.words_file):
		raise Exception("File with the words doesn't exist")
	if not os.path.exists(args.dict_file):
		raise Exception("Dictionary directory doesn't exist")
	if not os.path.exists(args.out_dir):
		raise Exception("Output directory doesn't exist")
	if args.test=='lazyEWBST':
		if not os.path.exists(args.rows):
			raise Exception("Lazy rows directory doesn't exist")
		if int(args.number)<=0:
			raise Exception("Close path value must be grater than 0")
	if int(args.detractors)<1:
		raise Exception("Decractors value must be grater than 0")
	if int(args.threshold)<1:
		raise Exception("Threshold value must be grater than 0")
	if args.seed!=None:
		args.seed=int(args.seed)
			
	
	main(args.words_file, args.dict_file, args.out_dir, args.test_name, int(args.threshold), args.flex, int(args.detractors), args.test,
		args.user, args.passwd, args.host, args.db, int(args.port), args.seed, args.rows)

