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


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

	data = scx.ScxData(input_file)
	translations = translator.load_translations(translations_file, fix_quotes=True, fix_two_spaces=True)
	translations_map = {translator.normalize_translation_key(x):y for x, y in translations}

	if len(data.labels) != 3 or len(data.savepoints) != 0:
		raise Exception("invalid labels count")
	output = scx.OutputBuilder(data.num_strings())
	output.add_code(data.content[data.eip:data.labels[0]]) # init code
	output.add_label(output.get_code_pos(data.eip))
	output.add_code(data.content[data.labels[0]:data.labels[1]]) # system string indices
	output.add_label(output.get_code_pos(data.eip))
	chars1_index, chars2_index = struct.unpack_from('<HH', data.content, data.labels[1])
	chars1 = data.parse_text(chars1_index)
	chars2 = data.parse_text(chars2_index)
	i = data.content.find(b'\xFF\xFF', data.labels[1] + 4)
	chars2_to_chars1 = struct.unpack_from('<' + str((i - data.labels[1] - 4) // 2) + 'H', data.content, data.labels[1] + 4)
	j = data.content.find(b'\xFF\xFF', i + 2)
	chars1_to_contents = struct.unpack_from('<' + str((j - i - 2) // 2) + 'H', data.content, i + 2)
	if j + 2 != data.labels[2]:
		raise Exception("invalid tips structure")
	if translator.enable_cyrillic:
		chars1 = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@β'
		chars2 = 'аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯaAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789@β'
		chars2_to_chars1 = [[i,i] for i in range(6)] + [[5,5]] + [[6+i,6+i] for i in range(26)] + [[32+i,32+i] for i in range(26)] + [[58+i] for i in range(12)]
		chars2_to_chars1 = [x for group in chars2_to_chars1 for x in group]
		chars1_to_contents = [i//4 for i in range(32)] + [8]*26 + [9]*12
		chars1_to_contents[chars1.index('Ь')] -= 1
	output.add_code(struct.pack('<HH', chars1_index, chars2_index))
	output.add_code(struct.pack('<' + str(len(chars2_to_chars1)) + 'H', *chars2_to_chars1) + b'\xFF\xFF')
	output.add_code(struct.pack('<' + str(len(chars1_to_contents)) + 'H', *chars1_to_contents) + b'\xFF\xFF')
	output.add_label(output.get_code_pos(data.eip))
	output.add_code(data.content[data.labels[2]:data.strings_table])
	for i in range(data.num_strings()):
		if i == chars1_index:
			output.serialize_text(chars1)
			continue
		if i == chars2_index:
			output.serialize_text(chars2)
			continue
		if i >= 20 and i < 29:
			first = min(pos for pos,idx in enumerate(chars1_to_contents) if idx == i - 20)
			last = max(pos for pos,idx in enumerate(chars1_to_contents) if idx == i - 20)
			output.serialize_text([chars1[first], 396, chars1[last]])
			continue
		if i == 29:
			output.serialize_text('Цифры и спецсимволы')
			continue
		text = data.parse_text(i)
		if i <= 17:
			output.serialize_text(text)
			continue
		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 key in translations_map:
			text = scx.string_to_text(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_tips('script/' + sys.argv[1], sys.argv[2], 'translated_script/' + sys.argv[1])
