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

from __future__ import unicode_literals, print_function
from frappe.utils.minify import JavascriptMinify
import subprocess
import warnings

from six import iteritems, text_type

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

import os, frappe, json, shutil, re

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, restore=False, verbose=False):
	"""concat / minify js files"""
	# build js files
	setup()

	make_asset_dirs(make_copy=make_copy, restore=restore)

	# new nodejs build system
	command = 'node --use_strict ../apps/frappe/frappe/build.js --build'
	if not no_compress:
		command += ' --minify'
	subprocess.call(command.split(' '))

	# build(no_compress, verbose)

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

	# new nodejs file watcher
	command = 'node --use_strict ../apps/frappe/frappe/build.js --watch'
	subprocess.call(command.split(' '))

	# 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, restore=False):
	# don't even think of making assets_path absolute - rm -rf ahead.
	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 os.path.exists(source):
				if restore:
					if os.path.exists(target):
						if os.path.islink(target):
							os.unlink(target)
						else:
							shutil.rmtree(target)
						shutil.copytree(source, target)
				elif make_copy:
					if os.path.exists(target):
						warnings.warn('Target {target} already exists.'.format(target = target))
					else:
						shutil.copytree(source, target)
				else:
					if os.path.exists(target):
						if os.path.islink(target):
							os.unlink(target)
						else:
							shutil.rmtree(target)
					os.symlink(source, target)
			else:
				warnings.warn('Source {source} does not exist.'.format(source = source))

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

	for target, sources in iteritems(get_build_maps()):
		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 iteritems(json.loads(f.read())):