# -*- coding: UTF-8 -*-
from __future__ import print_function, unicode_literals
import io, sys, os, struct, logging
import scx, translator


def translate_mail(input_file, translations_file, output_file):
	logger = logging.getLogger(os.path.basename(input_file))
	scx.load_characters_data('input_map.bin', translator.enable_cyrillic)

	data = scx.ScxData(input_file)
	translations = translator.load_translations(translations_file, fix_quotes=True, fix_em_dash=True)
	translations_map = {translator.normalize_translation_key(x):y for x, y in translations}
	if len(translations_map) != len(translations):
		logger.warning("duplicate translation detected")
		translator.num_warnings += 1

	output = scx.OutputBuilder(data.num_strings())
	output.add_code(data.content[data.eip:data.strings_table])
	for label in data.labels:
		output.add_label(label)
	for savepoint in data.savepoints:
		output.add_savepoint(savepoint)
	for i in range(data.num_strings()):
		text = data.parse_text(i)
		original_key = scx.text_to_string(text)
		key = translator.normalize_translation_key(original_key)
		if ("[id:%d]" % i + key) in translations_map:
			key = "[id:%d]" % i + key
		if text == [] or text == ["\u3000"]:
			output.serialize_text(text)
			continue
		pos = -1
		translated = ''
		while True:
			pos = key.find('[br]', pos + 1)
			if pos == -1:
				break
			if key[:pos] in translations_map:
				translated = translated + translations_map[key[:pos]]
				while key[pos:pos+4] == '[br]':
					translated += '[br]'
					pos += 4
				key = key[pos:]
				pos = -1
		if key in translations_map:
			text = scx.string_to_text(translated + translations_map[key])
		else:
			logger.warning("no translation for [id:" + str(i) + "]: " + original_key)
			translator.num_warnings += 1
		output.serialize_text(text)
	with io.open(output_file, 'wb') as f:
		output.save(f)


if __name__ == "__main__":
	logging.basicConfig()
	translate_mail('script/' + sys.argv[1], sys.argv[2], 'translated_script/' + sys.argv[1])
