"""
Dracu-riot! Inserter

How to use:
  Place .scn and corresponding .txt files in the same directory.
  Run on all .scn files in the directory by doing the following:
  
    insert.py directory\*.scn
  
"""

import glob
import os
import re
import struct
import sys
import zlib

import psb

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

def get_lines(scn_file, txt_file):
	texts = {}
	data, is_comp = psb.get_data(scn_file)
	psbobj = psb.get_psb(data)
	textlist = psb.get_texts(psbobj)
	for id, text in enumerate(textlist):
		texts[id] = text
	jtext = None
	text = None
	new_texts = {}
	for line in open(txt_file, 'r', encoding='utf-8'):
		line = line.strip()
		if not line:
			continue
		if re_jline.match(line):
			dummy, jtext = re_jline.match(line).groups()
		if re_line.match(line):
			idx, text = re_line.match(line).groups()
			idx = int(idx, 16)
			if idx in new_texts:
				if jtext != text:
					new_texts[idx] = text.replace('\\n','\n')
			else:
				new_texts[idx] = text.replace('\\n','\n')
	texts.update(new_texts)
	outtexts = []
	for id in sorted(texts):
		outtexts.append(texts[id])
	return outtexts
	
def insert(out_file, scn_file, txt_file):
	texts = get_lines(scn_file, txt_file)
	data, is_comp = psb.get_data(scn_file)
	psbobj = psb.get_psb(data)
	textptrblock, textblock = psb.make_texts(texts)
	opsbobj = psbobj._replace(textptrblock=textptrblock, textblock=textblock)
	odata = psb.make_psb(opsbobj)
	psb.write_data(out_file, odata, is_comp)

def is_current(ofile,ifile):
	mt = os.path.getmtime
	if not os.access(ofile, os.F_OK):
		return False
	if mt(ofile) < mt(ifile):
		return False
	return True

if __name__ == '__main__':
	if len(sys.argv) < 3:
		print('Usage: insert.py <out_dir> <txtfiles>')
		exit(1)
	outdir = sys.argv[1]
	if not os.access(outdir, os.F_OK):
		os.mkdir(outdir)
	for arg in sys.argv[2:]:
		for txt_file in glob.glob(arg):
			if os.path.splitext(txt_file)[1].lower() == '.txt':
				scn_file = os.path.splitext(txt_file)[0] + '.scn'
				if not os.access(scn_file, os.F_OK):
					continue
				out_file = os.path.join(outdir, os.path.split(scn_file)[1])
				if not is_current(out_file, txt_file):
					print('Inserting into {}...'.format(out_file))
					insert(out_file, scn_file, txt_file)
