#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, os.path, sys, argparse, codecs, ConfigParser

def replace_flex(tuples, output, left_dict, right_dict):
	all_tuples = []
	file = codecs.open(tuples, "r", 'utf-8')
	lines = file.readlines()
	no_lines = len(lines)
	file.close()
	processed = 0
	for line in lines:
		processed += 1
		if (processed % 1000000)==0:
			print "Processed %d/%d"%(processed, no_lines)
		isChanged = False
		parts = line.split(';')
		left_word = parts[0].split(':') 
		right_word = parts[2].split(':') 
		left_flex = left_word[0]
		right_flex = right_word[0]
		if (left_flex in left_dict):
			left_word[0] = left_dict[left_flex]
			parts[0] = ':'.join(left_word)
			isChanged = True
		if (right_flex in right_dict):
			right_word[0] = right_dict[right_flex]
			parts[2] = ':'.join(right_word)
			isChanged = True
		if isChanged:
			line = ';'.join(parts)
		all_tuples.append(line)
	print "Writing file..."
	out = codecs.open(output, 'w', 'utf-8')
	for tuples  in all_tuples:
		out.write(tuples)
	out.close()
	print "Done"

def create_dictionaries(replace_file):
	left_dict = {}
	right_dict = {}
	file = codecs.open(replace_file, "r", 'utf-8')
	lines = file.readlines()
	file.close()
	for line in lines:
		options = line.split(';');
		flex_list = options[0].split(',')
		alias = options[1]
		side = int(options[2])
		for flex in flex_list:	
			if side == -1:
				left_dict[flex] = alias
			elif side == 1:
				right_dict[flex] = alias
			else:
				sys.exit("Wrong side value")
	return left_dict, right_dict

def main():
	parser = argparse.ArgumentParser(description=' Program replace flex part of the word in tuples')
	parser.add_argument('--tuples', action='store', help='Path to tuples file')
	parser.add_argument('--output', action='store', help='Path to output file')
	parser.add_argument('--replace', action='store', help='Path to file with flex to replace. Line format in file: "flex1,flex2,flex3;alias;side", where side = -1 for left word and side = 1 for right ')
	
	args = parser.parse_args()
	if args.output==None:
		sys.exit("You need to set --output")
	if args.tuples==None:
		sys.exit("You need to set --tuples")
	if args.replace==None:
		sys.exit("You need to set --replace")
	
	if not os.path.exists(args.tuples):
		sys.exit("Tuples file doesn't exist")
	if not os.path.exists(args.replace):
		sys.exit("Replace file doesn't exist")
	
	left, right = create_dictionaries(args.replace)
	replace_flex(args.tuples,args.output, left, right )

if __name__ == "__main__":
	main()
