# Copyright AllSeen Alliance. All rights reserved.
#
#    Permission to use, copy, modify, and/or distribute this software for any
#    purpose with or without fee is hereby granted, provided that the above
#    copyright notice and this permission notice appear in all copies.
#
#    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# 

import os
import subprocess
import sys
import time

Import('env')

# Dependent Projects
if not env.has_key('_ALLJOYNCORE_'):
    env.SConscript('../alljoyn_core/SConscript')

jsenv = env.Clone()

if jsenv['BR'] == 'on':
    # Build JS with bundled daemon support
    jsenv.Prepend(LIBS = [jsenv['ajrlib']])

jsenv['OBJDIR_ALLJOYN_JS'] = env['OBJDIR'] + '/alljoyn_js'

vars = Variables()
vars.Add(PathVariable('CORDOVA_BASE', 'Base directory of Cordova (aka PhoneGap)', os.environ.get('CORDOVA_BASE')))
vars.Add(PathVariable('GECKO_BASE', 'Base directory of Gecko SDK', os.environ.get('GECKO_BASE')))
vars.Add(PathVariable('JSDOC_DIR', 'The path to the JsDoc toolkit', os.environ.get('JSDOC_DIR'), PathVariable.PathIsDir))
vars.Add(PathVariable('WIDLPROC', 'Path to widlproc executable', os.environ.get('WIDLPROC')))
vars.Add(PathVariable('XSLTPROC', 'Path to xsltproc executable', 'xsltproc', PathVariable.PathAccept))
vars.Update(jsenv)
Help(vars.GenerateHelpText(jsenv))

# JavaScript requires a couple of header files in alljoyn_core/src
jsenv.Append(CPPPATH = [jsenv.Dir('../alljoyn_core/src').srcnode()])

if '' == jsenv.subst('$GECKO_BASE') and '' == jsenv.subst('$CORDOVA_BASE'):
    print 'Must specify either GECKO_BASE or CORDOVA_BASE build variable'
    if not GetOption('help'):
        Exit(1)

sys.path.append(str(jsenv.Dir('../build_core/tools/scons').srcnode()))
from jsstatus import JavaScriptStatus
from widl import Widl

if not jsenv.has_key('BULLSEYE_BIN'):
    print('BULLSEYE_BIN not specified')
else:
    jsenv.PrependENVPath('PATH', jsenv.get('BULLSEYE_BIN'))

if jsenv.has_key('JSDOC_DIR'):
    jsenv.PrependENVPath('PATH', jsenv.get('JSDOC_DIR'))

# add support for NPAPI plugins
jsenv.Append(CPPDEFINES = '__STDC_LIMIT_MACROS')
if jsenv['OS_CONF'] == 'windows':
    jsenv.Append(CPPDEFINES = ['_WINDOWS', 'WIN32'])
    if jsenv['CPU'] == 'x86_64':
        jsenv.Append(CPPDEFINES = 'WIN64')

# TODO
# LOCAL_CFLAGS += -fvisibility=hidden
# LOCAL_PRELINK_MODULE:=false

# Make alljoyn_js dist a sub-directory of the alljoyn dist.  This avoids any conflicts with alljoyn dist targets.
jsenv['JS_DISTDIR'] = jsenv['DISTDIR'] + '/js'

# Add support for mulitiple build targets in the same workset
jsenv.VariantDir('$OBJDIR_ALLJOYN_JS/jni', 'jni', duplicate = 0)

# AllJoyn JavaScript status codes
JavaScriptStatus('jni/Status.xml', 'jni/BusErrorInterface.cc')

# AllJoyn plugin library
libs = jsenv.SConscript('$OBJDIR_ALLJOYN_JS/jni/SConscript', exports = {'env': jsenv})
if '' != jsenv.subst('$GECKO_BASE'):
    jsenv.Install('$JS_DISTDIR/lib', libs)
else:
    jsenv.Install('$JS_DISTDIR/libs/armeabi', libs)

# AllJoyn Cordova plugin - Java side
if '' != jsenv.subst('$CORDOVA_BASE'):
    jsenv.SConscript('src/SConscript', exports = {'env': jsenv})

# AllJoyn samples
jsenv.SConscript('samples/SConscript', exports = {'env': jsenv})

# Plugin distributions
if '' != jsenv.subst('$GECKO_BASE'):
    if jsenv['OS_CONF'] == 'windows':
        jsenv.Install('$JS_DISTDIR/plugin', ['alljoyn64.reg', 'alljoyn.reg', '$JS_DISTDIR/lib/npalljoyn.dll'])
# TODO
#    Widl('assets/www/alljoyn.js.in', 'jni/Status.xml', 'assets/www/alljoyn.js')
#    jsenv.Install('$JS_DISTDIR/assets/www', 'assets/www/alljoyn.js')

# Build docs
if jsenv['DOCS'] == 'html':
    jsenv.SConscript('docs/SConscript')

def widlproc_cmd(widl, wxml):
    xml = open(wxml, 'w')
    p = subprocess.Popen(jsenv['WIDLPROC'] + ' ' + widl, shell=True, stdout=xml)
    p.wait()
    xml.flush()
    xml.close()

if 'WIDLPROC' in jsenv:
    print("*******************************************************************")
    print("* Documentation generated using widlproc has been DEPRECATED      *")
    print("* please switch to JsDoc3                                         *")
    print("*******************************************************************")
    footer = '"<hr/><p class=\\"copyright\\"></p><small>AllJoyn&trade; JavaScript API Reference Manual Version 15.04.00b ' + time.strftime('%a %B %d %H:%M:%S %Z %Y') + '<br/>Copyright AllSeen Alliance, Inc.<br/><p>AllSeen, AllSeen Alliance, and AllJoyn are trademarks of the AllSeen Alliance, Inc in the United States and other jurisdictions.<br/></p><b>THIS DOCUMENT AND ALL INFORMATION CONTAIN HEREIN ARE PROVIDED ON AN \\"AS-IS\\" BASIS WITHOUT WARRANTY OF ANY KIND</b>.<br/><b>MAY CONTAIN U.S. AND INTERNATIONAL EXPORT CONTROLLED INFORMATION</b><br/></small>"'
    Widl('docs/alljoyn.widl.in', 'jni/Status.xml', 'docs/alljoyn.widl')
    # The target directory 'docs/tmp' is never built this will cause the command to run every time WIDLPROC=foo is set
    Command('docs/tmp', 'docs/alljoyn.widl', [
            widlproc_cmd('docs/alljoyn.widl', 'docs/alljoyn.wxml'),
            jsenv['XSLTPROC'] +
            ' --stringparam date "' + time.strftime('%d %B %Y') + '"' +
            ' --stringparam footer ' + footer +
            ' --path ' + os.path.dirname(jsenv['WIDLPROC']) +
            ' -o ' + File('docs/html/index.html').path +
            ' ' + File(os.path.dirname(jsenv['WIDLPROC']) + '/../src/widlprocxmltohtml.xsl').path +
            ' ' + File('docs/alljoyn.wxml').path
            ])
    css = jsenv.Install('docs/html', 'docs/widlhtml.css')
    # make sure the output from widlproc is cleaned
    jsenv.Clean([css], env.Dir('docs/html'))

