import glob
import os
import pickle
import re
import sys

import psb

re_line = re.compile(r'<([0-9A-Fa-f]+)>(.*)')

aliasfile = 'aliastbl.txt'

def read_aliastbl():
	aliastbl = {}
	for line in open(aliasfile, 'r', encoding='utf-8'):
		line = line.strip()
		curscene, id, curline, text = line.split('::::')
		id = int(id, 16)
		curline = int(curline)
		aliastbl[(curscene, curline)] = (id, text)
	return aliastbl
	
aliastbl = read_aliastbl()

def get_scenes(txtfile, allscenes):
	scenes = []
	fname = os.path.split(txtfile)[1]
	scnfile = os.path.splitext(txtfile)[0] + '.scn'
	data, is_comp = psb.get_data(scnfile)
	psbobj = psb.get_psb(data)
	objectblock = psbobj.objectblock
	org_texts = psb.get_texts(psbobj)
	org_names = psb.get_names(psbobj)
	org_chunks = psb.get_chunks(psbobj)
	expr = psb.get_expr(objectblock, org_names, org_texts, org_chunks)
	if 'scenes' not in expr:
		return scenes
	for scene in expr['scenes']:
		curscene = expr['name'] + scene['label']
		scenes.append(curscene)
	allscenes[fname] = scenes
	return scenes

def process_script(fs, txtfile, allscenes):
	fname = os.path.split(txtfile)[1]
	if allscenes and fname in allscenes:
		scenes = allscenes[fname]
	else:
		scenes = get_scenes(txtfile, allscenes)
	scenes = iter(scenes)
	curscene = None
	for line in open(txtfile, 'r', encoding='utf-8'):
		line = line.strip()
		if line.startswith('///========'):
			if curscene:
				fs.write('\t],\n')
			try:
				curscene = next(scenes)
			except StopIteration:
				break
			fs.write('\t"{}" => %[\n'.format(curscene.replace('"','\\"')))
			curline = 0
		elif re_line.match(line) and curscene:
			id, text = re_line.match(line).groups()
			if (curscene, curline) in aliastbl:
				fs.write('\t\t{} => "{}",\n'.format(curline + 1, text.replace('"','\\"')))
			curline += 1

if __name__ == '__main__':
	if len(sys.argv) < 2:
		print('Usage: make_textsub.py <txt_files>')
		exit(1)
	if os.access('allscenes.pickle', os.F_OK):
		allscenes = pickle.load(open('allscenes.pickle', 'rb'))
	else:
		allscenes = {}
	fs = open('textsub.tjs', 'w', encoding='cp932')
	fs.write('%[\n')
	for arg in sys.argv[1:]:
		for file in glob.glob(arg):
			if os.path.splitext(file)[1].lower() == '.txt':
				print('Processing {}...'.format(file))
				process_script(fs, file, allscenes)
	fs.write(']\n')
	fs.close()
	pickle.dump(allscenes, open('allscenes.pickle', 'wb'))
