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

log_untranslated_strings = False

def translate_strings(input_file, translations_file, output_file):
	logger = logging.getLogger(os.path.basename(input_file))
	scx.load_characters_data('input_map.bin', translator.enable_cyrillic)
	input_data = scx.ScxData(input_file)
	translations = translator.load_translations(translations_file, fix_quotes=True, fix_two_spaces=False)
	translations_map = {translator.normalize_translation_key(x):y for x, y in translations}

	output = scx.OutputBuilder(input_data.num_strings())
	output.add_code(input_data.content[input_data.eip:input_data.strings_table])
	for label in input_data.labels:
		output.add_label(label)
	for savepoint in input_data.savepoints:
		output.add_savepoint(savepoint)
	for i in range(input_data.num_strings()):
		#text = scx.parse_text(input_data.content, input_data.strings_table, i)
		text = input_data.parse_text(i)
		if i <= 1 and translator.enable_cyrillic and input_file.lower().endswith('system.scx'):
			if len(text) != 1:
				raise Exception("expected single string")
			if i == 0:
				text[0] += '»'
			else:
				text[0] += '«№'
			output.serialize_text(text)
			continue
		key = scx.text_to_string(text)
		normalized = translator.normalize_translation_key(key)
		if normalized in translations_map:
			text = scx.string_to_text(translations_map[normalized])
		elif log_untranslated_strings:
			logger.warning("no translation for [id:" + str(i) + "]: " + 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_strings('script/' + sys.argv[1], sys.argv[2], 'translated_script/' + sys.argv[1])
