import os
import sys
import codecs
import argparse
try:
	import argcomplete
except ImportError:
	argcomplete = None

def make_parser():
	desc = "Budowa grafu SUMO na podstawie podanego zbioru plikow w formacie .kif"
	parser = argparse.ArgumentParser(description = desc) 
	parser.add_argument('-d', '--sumo-dir', dest = 'sumo_dir', required = True)
	parser.add_argument('-i', '--index-file', dest = 'index_file', required = True)
	parser.add_argument('-o', '--out-file', dest = 'out_file', required = True)

	if argcomplete:
		argcomplete.autocomplete(parser)

	return parser

def read_sumo_files(sdir, sfile):
	files = []
	with codecs.open(os.path.join(sdir, sfile)) as fin:
		for f in fin:
			files.append(os.path.join(sdir, f.strip()))
	return files

def make_graph(files, out_file):
	relations = {}

	for f in files:
		print >> sys.stderr, f

		with codecs.open(f, 'rt') as sfile:
			for line in sfile:
				if line.startswith('(subclass') or line.startswith('(subrelation') or line.startswith('(instance') or line.startswith('(subAttribute'):
					while line.find('  ') != -1:
						line = line.replace('  ', ' ')

					#line = line.replace('(', '').replace(')', '')
					#spl_line = line.split(' ')
					spl_line_by_bracket = line.split(')')

					if len(spl_line_by_bracket) != 2:
						continue

					spl_line_by_bracket[0] = spl_line_by_bracket[0].replace('(', '').replace(')', '')
					spl_line = spl_line_by_bracket[0].split(' ')
					parent = spl_line[2].strip()
					child = spl_line[1].strip()
					relation = spl_line[0].strip()

					if not relations.has_key(parent):
						relations[parent] = {child:relation}
					else:
						if not relations[parent].has_key(child):
							relations[parent][child] = relation
						else:
							if relations[parent][child] == relation:
								print >> sys.stderr, 'Znowu ta sama relacja!'
							else:
								print >> sys.stderr, 'Jest relacja', relations[parent][child], ',a teraz pojawila sie relacja ', relation

	with codecs.open(out_file, 'wt') as sout:
		for k1 in relations.keys():
			r = relations[k1]
			for k2 in r.keys():
				sout.write('%s;%s;%s\n' % (k1, k2, r[k2]))

def main(argv = None):
	parser = make_parser()
	args = parser.parse_args(argv)

	files = read_sumo_files(args.sumo_dir, args.index_file)
	make_graph(files, args.out_file)

if __name__ == '__main__':
	main()
