#!/usr/bin/python
# -*- coding: utf-8 -*-

# <read before use>
#
# This script will:
# - read all pianos4*.js and imageeditor*.js files
# - remove all calls to assert() and log()
# - build a big, global script
# - feed this script to the Google closure compiler
# - print the result to stdout
#
# To use this script, you must:
#   1. Install the Google closure compiler (compiler.jar) in this directory
#   2. Have a running Java implementation (path hardcoded below, change it as needed)
#
# Example:
#   $ python minimize.py > pianos4.min.js
#
# Download the compiler at: https://developers.google.com/closure/compiler/
#
# </read before use>

import sys
import os
import cStringIO as StringIO
import subprocess
import re

def main(components=['pianos4','imageeditor'], jsDir='../js', noPrint=False, saveBeforeMin=None, postProcess=None):
	
	#javaExe = "C:\\Program Files\\Java\\jre1.8.0_66\\bin\\java.exe"
	javaExe = 'c:\\Program Files\\Java\\jre8-portable\\bin\\java.exe' # damn
	if not os.path.isfile(javaExe):
		javaExe = 'c:\\Program Files (x86)\\Java\\jre7\\bin\\java.exe'
		if not os.path.isfile(javaExe):
			javaExe = 'c:\\dev\\local\\jre7\\bin\\java.exe'
	files = os.listdir(jsDir)

	stripFuncalls = ['assert','log']
	
#	file('test-before.txt','wb').close()
#	file('test-after.txt','wb').close()

	commonFiles = ('pianos4_common.js',)
	
	to_merge = []
	
	output = StringIO.StringIO()
	for name in files:
		
		if name.find('.min.js') != -1:
			continue
		
		for comp in components:
			if name in commonFiles or name.find(comp) == 0:
				to_merge.append(name)
				break

	if postProcess:
		to_merge = postProcess(to_merge)
		
	for name in to_merge:
		sys.stderr.write("  Processing "+name+"\n")
		output.write("/* "+name+" */\n")
		content = file(os.path.join(jsDir,name),'r').read()

		#file('test-before.txt','ab').write(content+'\n\n')
		for f in stripFuncalls:
			content = re.sub('((?<![\.\w])'+f+'\(.*\);)', '', content)
		#file('test-after.txt','ab').write(content+'\n\n')
		
		output.write(content)
		output.write("\n\n")
	
	sys.stderr.write("Running the Google closure compiler\n")
	
	compiler = subprocess.Popen([javaExe,'-jar','compiler.jar','--compilation_level','SIMPLE_OPTIMIZATIONS','--jscomp_off','internetExplorerChecks'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	(out,err) = compiler.communicate(output.getvalue())

	if compiler.returncode != 0:
		sys.stderr.write("Compilation failed ! Errors:\n")
		sys.stderr.write(str(err)+'\n')
		file('merged-source.js','w').write(output.getvalue())
		sys.stderr.write("The merged source has been saved to 'merged-source.js' (line numbers reported above are relative to this file)")
		return None if onPrint else 1
	
	if saveBeforeMin:
		file(saveBeforeMin,'w').write(output.getvalue())
	
	header = '/*\n'+file('copyright-license-header.txt').read()+'\n*/\n'
	
	if noPrint:
		sys.stderr.write("Compilation successful !")
		return header+out
		
	else:
		print header
		print out
		sys.stderr.write("Compilation successful ! Output has been written to stdout\n")
		return 0
	
if __name__ == '__main__':
	if len(sys.argv) > 1:
		sys.exit(main(sys.argv[1:]))
	else:
		sys.exit(main())
