# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt

from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify

"""
Build the `public` folders and setup languages
"""

import os, frappe, json, shutil, re
# from cssmin import cssmin


app_paths = None
def setup():
	global app_paths
	pymodules = []
	for app in frappe.get_all_apps(True):
		try:
			pymodules.append(frappe.get_module(app))
		except ImportError: pass
	app_paths = [os.path.dirname(pymodule.__file__) for pymodule in pymodules]

def bundle(no_compress, make_copy=False, verbose=False):
	"""concat / minify js files"""
	# build js files
	setup()

	make_asset_dirs(make_copy=make_copy)
	build(no_compress, verbose)

def watch(no_compress):
	"""watch and rebuild if necessary"""
	setup()

	import time
	compile_less()
	build(no_compress=True)

	while True:
		compile_less()
		if files_dirty():
			build(no_compress=True)

		time.sleep(3)

def make_asset_dirs(make_copy=False):
	assets_path = os.path.join(frappe.local.sites_path, "assets")
	for dir_path in [
			os.path.join(assets_path, 'js'),
			os.path.join(assets_path, 'css')]:

		if not os.path.exists(dir_path):
			os.makedirs(dir_path)

	# symlink app/public > assets/app
	for app_name in frappe.get_all_apps(True):
		pymodule = frappe.get_module(app_name)
		app_base_path = os.path.abspath(os.path.dirname(pymodule.__file__))

		symlinks = []
		symlinks.append([os.path.join(app_base_path, 'public'), os.path.join(assets_path, app_name)])
		symlinks.append([os.path.join(app_base_path, 'docs'), os.path.join(assets_path, app_name + '_docs')])

		for source, target in symlinks:
			source = os.path.abspath(source)
			if not os.path.exists(target) and os.path.exists(source):
				if make_copy:
					shutil.copytree(source, target)
				else:
					os.symlink(source, target)

def build(no_compress=False, verbose=False):
	assets_path = os.path.join(frappe.local.sites_path, "assets")

	for target, sources in get_build_maps().iteritems():
		pack(os.path.join(assets_path, target), sources, no_compress, verbose)

def get_build_maps():
	"""get all build.jsons with absolute paths"""
	# framework js and css files

	build_maps = {}
	for app_path in app_paths:
		path = os.path.join(app_path, 'public', 'build.json')
		if os.path.exists(path):
			with open(path) as f:
				try:
					for target, sources in json.loads(f.read()).iteritems():
						# update app path
						source_paths = []
						for source in sources:
							if isinstance(source, list):
								s = frappe.get_pymodule_path(source[0], *source[1].split("/"))
							else: