#sem:name: Java applet
#sem:tip: Generates a web applet in java (requires java)
#sem:picture

# Thomas Nagy, 2007-2019 GPLV3

import os, shutil, time, sys

# TODO for the moment it does not work

outdir = sembind.get_var('outdir')+'/'+sembind.get_var('pname')

try:
	os.makedirs(outdir + '/pics')
except OSError:
	sys.stderr.write("Cannot create the pics folder in %s" % outdir)

for x in "run.sh Makefile main.html Kadapplet.java Mapview.java".split():
	shutil.copy2(template_dir() + '/java/'+x, outdir)
os.chmod(os.path.join(outdir, 'run.sh'), 0o755)

# copy the pictures
temp_dir = sembind.get_var('temp_dir')
pics = {} # map the id to the picture
lst = os.listdir(temp_dir)
for x in lst:
	if x.startswith('diag-') or x.startswith('wholemap'):
		key = x.split('.')[0].replace('diag-', '')
		pics[key] = x
		shutil.copy2(os.path.join(temp_dir, x), outdir + '/pics')

code = []
def out(s):
	global code
	code.append(s)

def low_coords(node):
	x = float(node.get_val('x'))
	y = float(node.get_val('y'))

	num = node.child_count()
	for i in range(num):
		x2, y2 = low_coords(node.child_num(i))
		if x2 < x:
			x = x2
		if y2 < y:
			y = y2
	return (x, y)

def print_rec(node, X, Y):
	x = float(node.get_val('x')) - X
	y = float(node.get_val('y')) - Y
	w = float(node.get_val('w'))
	h = float(node.get_val('h'))

	if node.get_val('type') == 'text':
		txt = node.get_val('text')
		txt = clear_html(txt)
		txt = repr(txt)[1:-1].replace('"', '\\"')

		s = '\nif (x > %f && y > %f && x < %f && y < %f) { return "%s"; }\n' % (x, y, x+w, y+w, txt)
		out(s)

	num = node.child_count()
	for i in range(num):
		print_rec(node.child_num(i), X, Y)

root = Root()
x, y = low_coords(root)

out("/** Generated by Semantik */\n\n")
out("public class TextCoord\n{\n")
out("public static String coordToText(double x, double y) {\n")
print_rec(root, x - 25, y - 25)
out("return \"\";\n")
out("}\n}\n")

with open(outdir+'/TextCoord.java', 'w', encoding='utf-8') as f:
	f.write(''.join(code))

