#!/usr/bin/python
# -*- coding: utf-8 -*-

import random, nltk

from generators.HWBST import WBSTQuestion
import wordsutils

def filter_words(words):
	out = set([])
	print "Filtering words"
	for word in words:
		if word in nltk.wordnet.N:
			out.add(word)
	print "Filtered size:", len(out)

	return out

def generate_test(candidate_words, detractors_words, no_of_detractors):
	"""
	Assumes that candidate_words are present in PWN!
	"""
	detractor_arr = sorted(detractors_words)
	qapairs = set([])
	questions = []
	l = len(candidate_words)
	curr = 0
	for w1 in candidate_words:
		synsets = nltk.wordnet.getWord(w1)
		synonyms = get_all_words(synsets)
		for w2 in synonyms:
			if not w2 in detractors_words or w1 == w2 or (w1,w2) in qapairs or (w2,w1) in qapairs:
				continue
			detractors = generate_detractors(w1,w2,no_of_detractors, detractor_arr, synonyms)
			if len(detractors) == no_of_detractors:
				question = WBSTQuestion(w1, w2, detractors)
				qapairs.add( (w1,w2) )
				questions.append(question)
		curr += 1
		if curr % 500 == 0:
			print "Generating question for %s / %s" % (curr, l)
	return questions

def get_all_words(synsets):
	words = set([])
	for s in synsets:
		for w in s:
			words.add(w)
	return words

def generate_detractors(q, a, no, arr, synonyms):
	random.shuffle(arr)
	detractors = set([])
	for w_no in xrange( len(arr) ):
		det = arr[w_no]
		if not det in synonyms:
			detractors.add(det)
		if len(detractors) == no:
			return detractors
	return detractors
	
def main(words_file, detractors, outdir, test_name):
	print "WBST for English test"
	words = wordsutils.load_words(words_file, 1)
	wnwords = filter_words(words)
	print "Generating test..."
	test = generate_test(wnwords, wnwords, int(detractors))
	print "Saving test..."
	wordsutils.save_questions(test, outdir + test_name + ".csv", 'utf8')
	


if __name__ == '__main__':
	import sys, argparse
	
	parser = argparse.ArgumentParser(description='WBST for English test')
	parser.add_argument('words_file',  action='store', 
		help='Path to the file with words for questions')
	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)')
	parser.add_argument('-D',action='store', dest='detractors', default=3,
		help='Number of detractors (default=3)')
	
	args = parser.parse_args()
	main(args.words_file, args.detractors, args.outdir, args.test_name)

