#!/usr/bin/python

import re, sys, codecs

def load_words(words_file, encoding = 'cp1250'):
	"""
	Loads file with words (one word per line) in given encoding.
	"""
	words = []
	for line in codecs.open(words_file, 'r', encoding):
		line = line.strip()
		if len(line) > 0:
			words.append(line)
	return sorted(words)

def load_config_lines(config_in):
	"""
	Reads config me_architect file. Returns tuple of (all_lines, words_tuples, matrix_name), where
	all_lines are non-empty lines without 'column-units' parameter, and 
	words_tuples are tuples of (joksipi_operator_file, words, flex_class)
	"""
	print "Reading config file:", config_in
	all_lines = []
	words_tuples = []
	matrix_name = ""
	
	column_units_patter = re.compile(r'\s*column-units\s*=(.+)\|(.+)\|(.+)')
	matrix_name_pattern = re.compile(r'\s*matrix-name\s*=(.+)')
	for line in open(config_in):
		line = line.strip()
		if len(line) == 0 or line[0] == '#':
			continue

		match = column_units_patter.match(line)
		if match:
			operator = match.group(1).strip()
			lex = match.group(2).strip()
			flex = match.group(3).strip()
			words = load_words( lex )
			print "Loaded %d words for %s (%s)" % (len(words), operator, flex)
			words_tuples.append( (operator, words, flex ) )
			continue
		match = matrix_name_pattern.match(line)
		if match:
			matrix_name = match.group(1).strip()
			continue

		all_lines.append( line )
	
	print "Matrix name:", matrix_name
	return (all_lines,words_tuples, matrix_name)

def prepare_dir( path ):
	"""
	Check wheter path exists, and is non-empty
	"""
	import os
	if not os.path.exists( path ):
		os.mkdir( path )
	else:
		print >> sys.stderr, "WARNING: path %s allready exists!" % path

def split_single_tuple( words, max_words ):
	if len(words) > max_words:
		return words[:max_words], words[max_words:]
	return words
	
def split_tuples(words_tuples, max_columns_per_process):
	tuples_out = []
	current_tuple_no = 0
	current_in_tuple = None
	while current_tuple_no != len(words_tuples):
		if not current_in_tuple:
			current_in_tuple = words_tuples[current_tuple_no]
		op, words, flex = current_tuple
		#TODO dokonczyc

	return tuples_out



def write_new_configs(config_lines, words_tuples, matrix_name, config_dir_out, max_columns_per_process):
	"""
	Writes new config files into directory config_dir_out. Configs are based on:
	config_lines - all non-empty lines, without matrix-name and column-units arguments
	words_tuples - tuples returned by load_config_lines
	max_columns_per_process - maximum number of column units in one config file
	"""
	prepare_dir(config_dir_out)
	split_tuples(words_tuples, max_columns_per_process)
	#TODO write out

def prepare_configs(config_in, config_dir_out, max_columns_per_process):
	# read config file
	config_lines, words_tuples, matrix_name = load_config_lines(config_in)
	# output new config files
	write_new_configs(config_lines, words_tuples, matrix_name, config_dir_out, max_columns_per_process)
	#TODO output config for joining of matrices
	#TODO output run script
	
	
def main(argv):
	if len(argv) != 4:
		print >> sys.stderr, "Usage: python %s config_file out-dir max_columns_per_process" % argv[0]
	else:
		prepare_configs(argv[1], argv[2], int(argv[3]) )

if __name__ == '__main__':
	main(sys.argv)
