'''
Created on May 26, 2010

@author: Bartosz Broda, bartosz.broda@pwr.wroc.pl
'''
import os, sys
from optparse import OptionParser

import pyplwn

COUSINS = 'cousins.csv'
LEX_REL_PAIRS = 'lex_rel_pairs.csv'
SYN_REL_PAIRS = 'syn_rel_pairs.csv'
SYNONYMS = 'synonyms.csv'

class PairsGen:
	"""
	Generates data in intermediate format. Will create flowing files in workdir:
	
	- cousins.csv containing lemmaA;lemmaB;LCS_synst;m,n in every line (needs filtering)
	- lex_rel_pairs.csv containing relation;lemmaA;lemmaB in every line (needs filtering)
	- syn_rel_pairs.csv containing relation;lemmaA;lemmaB in every line (needs filtering)
	- synonyms.csv containing lemmaA;lemmaB in every line (no need for filtering)
	
	Note, all files but synonyms.csv have headers 
	
	"""
	
	
	def __init__(self, db, workdir, cousin_pathgen_len = 2):
		self.db = db
		self.workdir = workdir
		self.cousin_pathgen_len = cousin_pathgen_len

	def cousins(self):
		cousins = pyplwn.utils.Cousins(self.db)
		cousins.extract_all_cousins(os.path.join(self.workdir, COUSINS), 
								self.cousin_pathgen_len)
	
	def lex_rels(self):
		utils = pyplwn.utils.Utils(self.db)
		utils.extract_pairs_in_lexical_relation(os.path.join(self.workdir, LEX_REL_PAIRS) ) 
	
	def synonyms(self):
		utils = pyplwn.utils.Utils(self.db)
		utils.extract_synonymy_pairs(os.path.join(self.workdir, SYNONYMS))
	
	def synset_rels(self):
		utils = pyplwn.utils.Utils(self.db)
		utils.extract_pairs_in_synset_relation(os.path.join(self.workdir, SYN_REL_PAIRS) )
		
	def generate_all(self):
		print "Cousins"
		self.cousins()
		print "Lexical relations"
		self.lex_rels()
		print "Synonyms"
		self.synonyms()
		print "Synset relations"
		self.synset_rels()
		
def main():
	parser = OptionParser()
	parser.add_option("-l", "--max-len", dest="maxlen", type='int', help="Maximum value for m and n for (m,n)-cousins", default=3)
	parser.add_option("-w", "--workdir", dest="workdir", default = 'workdir', help="Workdir file (directory will contain: cousins.csv, " +
					"lex_rel_pairs.csv, syn_rel_pairs.csv and synonyms.csv)")
	parser.add_option("-u", "--user", dest="user", default = 'plwn', help="Database user")
	parser.add_option("-H", "--host", dest="host", default = 'localhost', help="Database host")
	parser.add_option("-p", "--passwd", dest="passwd", default = 'plwn', help="Database password")
	parser.add_option("-d", "--db", dest="db", default = 'plwn', help="Database schema")
	parser.add_option("-P", "--port", dest="port", default = '3306', help="Database port")
	
	options = parser.parse_args(sys.argv)[0]
	
	if not os.path.exists(options.workdir):
		os.makedirs(options.workdir)

	db = pyplwn.database.Database(user = options.user, passwd = options.passwd, db =  options.db, host = options.host, port = int(options.port), encoding = "utf8" )
	gen = PairsGen(db, options.workdir, options.maxlen)
	gen.generate_all()

if __name__ == '__main__':
	main()

