#!/usr/bin/python
#encoding:utf8

__author__ = 'marlena'
from plumper.sumo.plwnpwnsumo_file import MappingFileOperator
import collections
import argparse
import sys
import codecs
import networkx as nx


class Corec(MappingFileOperator):
	def __init__(self, sumo_tree_file):
		MappingFileOperator.__init__(self)
		self._plwn_sumo_rels = None
		self.tree = nx.DiGraph()

		self.make_sumo_graph(sumo_tree_file)


	def __linefunc(self, synset_id, sumo_str):
		self._plwn_sumo_rels[synset_id].add(sumo_str)


	def make_sumo_graph(self, sumo_tree_file):
		with codecs.open(sumo_tree_file, 'rt') as fin:
			for line in fin:
				spl_line = line.split(';')
				self.tree.add_nodes_from([spl_line[1], spl_line[0]])
				self.tree.add_edge(spl_line[1], spl_line[0], rel = spl_line[2])


	def zakorkuj_mi_to(self, mapping_result_file, out_fileobj=sys.stdout):
		self._plwn_sumo_rels = collections.defaultdict(set)

		self.read_mapping_file(mapping_result_file,
								(u'synset_id_plwn', u'pojecie_sumo'),
								self.__linefunc)

		for synset_id in self._plwn_sumo_rels:
			if len(self._plwn_sumo_rels[synset_id]) > 1:
				self._plwn_sumo_rels[synset_id] = list(self._plwn_sumo_rels[synset_id])
				list_len = len(self._plwn_sumo_rels[synset_id])
				is_remove = False
				i = 0
				while i < list_len-1:
					if self.tree.has_node(self._plwn_sumo_rels[synset_id][i]):
						j = i + 1
						while j < list_len:
							if self.tree.has_node(self._plwn_sumo_rels[synset_id][j]):
								if nx.has_path(self.tree, 
											   self._plwn_sumo_rels[synset_id][i], 
											   self._plwn_sumo_rels[synset_id][j]):
									self._plwn_sumo_rels[synset_id].remove(
										self._plwn_sumo_rels[synset_id][j])
									list_len = list_len - 1
									continue
								elif nx.has_path(self.tree, 
												 self._plwn_sumo_rels[synset_id][j], 
												 self._plwn_sumo_rels[synset_id][i]):
									self._plwn_sumo_rels[synset_id].remove(
										self._plwn_sumo_rels[synset_id][i])
									list_len = list_len - 1
									is_remove = True
									break
							j = j + 1
						if is_remove:
							is_remove = False
							continue
					i = i + 1
					
		list_len = len(self._linebuffer)
		i = 0
		while i < list_len:
			synset_id = self._linebuffer[i][2]
			sumo_concept = self._linebuffer[i][8]
			if self._plwn_sumo_rels.has_key(synset_id):
				if not sumo_concept in self._plwn_sumo_rels[synset_id]:
					self._linebuffer.pop(i)
					list_len = list_len - 1
					continue
			i = i + 1

		self.print_contents(out_fileobj)


def main():
	argparser = argparse.ArgumentParser(description=__doc__)
	argparser.add_argument('mapping_result_file', help="csv file with " + 
													   "plWN -> SUMO " + 
													   "output")
	argparser.add_argument('sumo_tree_file', help="SUMO graph file, " +
												  "file format: " +
												  "parent;child;rel")

	args = argparser.parse_args()

	c = Corec(args.sumo_tree_file)
	c.zakorkuj_mi_to(args.mapping_result_file)


if __name__ == '__main__':
	main()