#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2015 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the original copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor the names of its contributors
#   may be used to endorse or promote products derived from this work without
#   specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors:
#         Cici,Li<cici.x.li@intel.com>
#         Lin, Wanming <wanming.lin@intel.com>

import os
import sys
import commands
import shutil
import glob
import fnmatch
import re
import json
reload(sys)
sys.setdefaultencoding("utf-8")
script_path = os.path.realpath(__file__)
const_path = os.path.dirname(script_path)
tool_path = const_path + "/../tools/"
plugin_tool = const_path + "/../tools/cordova-plugin-crosswalk-webview/"
testapp_path = "/tmp/cordova-sampleapp/"


def setUp():
    global ARCH, MODE, CORDOVA_VERSION, device, CROSSWALK_VERSION, CROSSWALK_BRANCH, PACK_TYPE

    device = os.environ.get('DEVICE_ID')

    if not device:
        print (" get env error\n")
        sys.exit(1)

    f_arch = open(const_path + "/../arch.txt", 'r')
    arch_tmp = f_arch.read()
    if arch_tmp.strip("\n\t") == "arm":
        ARCH = "arm"
    elif arch_tmp.strip("\n\t") == "x86":
        ARCH = "x86"
    else:
        print (
            " get arch error, the content of arch.txt should be 'arm' or 'x86'\n")
        sys.exit(1)
    f_arch.close()

    f_mode = open(const_path + "/../mode.txt", 'r')
    mode_tmp = f_mode.read()
    if mode_tmp.strip("\n\t") == "shared":
        MODE = "shared"
    elif mode_tmp.strip("\n\t") == "embedded":
        MODE = "embedded"
    else:
        print (
            " get mode error, the content of mode.txt should be 'shared' or 'embedded'\n")
        sys.exit(1)
    f_mode.close()

    f_version = open(const_path + "/../cordova-version", 'r')
    if f_version.read().strip("\n\t") != "3.6":
        CORDOVA_VERSION = "4.x"
    else:
        CORDOVA_VERSION = "3.6"
    f_version.close()

    if CORDOVA_VERSION == "4.x":
        f_pack_type = open(const_path + "/../pack-type", 'r')
        pack_type_tmp = f_pack_type.read()
        if pack_type_tmp.strip("\n\t") == "local":
            PACK_TYPE = "local"
        elif pack_type_tmp.strip("\n\t") == "npm":
            PACK_TYPE = "npm"
        else:
            print (
                " get pack type error, the content of pack-type should be 'local' or 'npm'\n")
            sys.exit(1)
        f_pack_type.close()

        with open(const_path + "/../VERSION", "rt") as pkg_version_file:
            pkg_version_raw = pkg_version_file.read()
            pkg_version_file.close()
            pkg_version_json = json.loads(pkg_version_raw)
            CROSSWALK_VERSION = pkg_version_json["main-version"]
            CROSSWALK_BRANCH = pkg_version_json["crosswalk-branch"]


def create(appname, pkgname, mode, sourcecodepath, replace_index_list, self):
    os.chdir(tool_path)
    if os.path.exists(os.path.join(tool_path, appname)):
        print "Existing %s project, try to clean up..." % appname
        do_remove(glob.glob(os.path.join(tool_path, appname)))
    print "Create project %s ----------------> START" % appname
    if CORDOVA_VERSION == "4.x":
        cmd = "cordova create %s %s %s" % (appname, pkgname, appname)
    else:
        if mode == "shared":
            cmd = "cordova/bin/create %s %s %s --xwalk-shared-library" % (
                appname, pkgname, appname)
        else:
            cmd = "cordova/bin/create %s %s %s" % (appname, pkgname, appname)
    createstatus = commands.getstatusoutput(cmd)
    self.assertEquals(0, createstatus[0])
    print "\nGenerate project %s ----------------> OK\n" % appname
    result = commands.getstatusoutput("ls")
    self.assertIn(appname, result[1])
    project_root = os.path.join(tool_path, appname)
    if CORDOVA_VERSION == "4.x":
        os.chdir(project_root)
        if not replace_key(os.path.join(project_root, 'config.xml'),
                           '<widget android-activityName="%s"' % appname, '<widget'):
            print "replace key '<widget' failed."
            return False
        if not replace_key(os.path.join(project_root, 'config.xml'),
                           '    <allow-navigation href="*" />\n</widget>', '</widget>'):
            print "replace key '</widget>' failed."
            return False

        print "Add android platforms to this project --------------> START"
        cordova_platform_cmd = "cordova platform add android"
        platformstatus = commands.getstatusoutput(cordova_platform_cmd)
        self.assertEquals(0, platformstatus[0])

        print "Install Crosswalk WebView Plugin --------------> START"
        version_cmd = ""
        if CROSSWALK_BRANCH == "beta":
            if MODE == "shared":
                version_cmd = "--variable XWALK_VERSION=\"org.xwalk:xwalk_shared_library_beta:%s\"" % CROSSWALK_VERSION
            else:
                version_cmd = "--variable XWALK_VERSION=\"org.xwalk:xwalk_core_library_beta:%s\"" % CROSSWALK_VERSION
        else:
            version_cmd = "--variable XWALK_VERSION=\"%s\"" % CROSSWALK_VERSION

        plugin_crosswalk_source = plugin_tool
        if PACK_TYPE == "npm":
            plugin_crosswalk_source = "cordova-plugin-crosswalk-webview"

        plugin_install_cmd = "cordova plugin add %s %s --variable XWALK_MODE=\"%s\"" \
                    % (plugin_crosswalk_source, version_cmd, mode)

        pluginstatus = commands.getstatusoutput(plugin_install_cmd)
        self.assertEquals(0, pluginstatus[0])

        if replace_index_list is not None and len(replace_index_list) >= 2:
            index_file_path = os.path.join(project_root, "www", "index.html")
            key = replace_index_list[0]
            content = replace_index_list[1]
            if not replace_key(index_file_path, content, key):
                print "replace key: " + key + " failed."
                return False
        if sourcecodepath is not None:
            do_remove(glob.glob(os.path.join(project_root, "www")))
            do_copy(sourcecodepath, os.path.join(tool_path, appname, "www"))
    else:
        if replace_index_list is not None and len(replace_index_list) >= 2:
            index_file_path = os.path.join(
                project_root,
                "assets",
                "www",
                "index.html")
            key = replace_index_list[0]
            content = replace_index_list[1]
            if not replace_key(index_file_path, content, key):
                print "replace key: " + key + " failed."
                return False
        if sourcecodepath is not None:
            do_remove(glob.glob(os.path.join(project_root, "assets", "www")))
            do_copy(
                sourcecodepath,
                os.path.join(
                    tool_path,
                    appname,
                    "assets",
                    "www"))

def buildGoogleApp(appname, sourcecodepath, self):
    os.chdir(tool_path)
    if os.path.exists(os.path.join(tool_path, appname)):
        print "Existing %s project, try to clean up..." % appname
        do_remove(glob.glob(os.path.join(tool_path, appname)))
    print "Build project %s ----------------> START" % appname
    if sourcecodepath is None:
        print "sourcecodepath can't be none"
        return False

    if checkContains(appname, "CIRC"):
        cordova_app = os.path.join(tool_path, "circ")
        create_cmd = "cca create " + appname + " --link-to circ/package"
    elif checkContains(appname, "EH"):
        cordova_app = os.path.join(tool_path, "workshop-cca-eh")
        create_cmd = "cca create " + appname + " --link-to workshop-cca-eh/workshop/step4"

    if os.path.exists(cordova_app):
        do_remove(glob.glob(cordova_app))
    if not do_copy(sourcecodepath, cordova_app):
        return False

    print create_cmd
    buildstatus = commands.getstatusoutput(create_cmd)
    self.assertEquals(0, buildstatus[0])
    os.chdir(os.path.join(tool_path, appname))

    print "Add android platforms to this project --------------> START"
    add_android_cmd = "cca platform add android"
    addstatus = commands.getstatusoutput(add_android_cmd)
    self.assertEquals(0, addstatus[0])

    print "uninstall webview default plugin from this project --------------> START"
    plugin_uninstall_webview = "cordova plugin remove cordova-plugin-crosswalk-webview"
    uninstallStatus = commands.getstatusoutput(plugin_uninstall_webview)
    self.assertEquals(0, uninstallStatus[0])

    print "Install Crosswalk WebView Plugin --------------> START"
    version_cmd = ""
    if CROSSWALK_BRANCH == "beta":
        if MODE == "shared":
            version_cmd = "--variable XWALK_VERSION=\"org.xwalk:xwalk_shared_library_beta:%s\"" % CROSSWALK_VERSION
        else:
            version_cmd = "--variable XWALK_VERSION=\"org.xwalk:xwalk_core_library_beta:%s\"" % CROSSWALK_VERSION
    else:
        version_cmd = "--variable XWALK_VERSION=\"%s\"" % CROSSWALK_VERSION

    plugin_crosswalk_source = plugin_tool
    if PACK_TYPE == "npm":
        plugin_crosswalk_source = "cordova-plugin-crosswalk-webview"

    plugin_install_cmd = "cordova plugin add %s %s --variable XWALK_MODE=\"%s\"" \
                % (plugin_crosswalk_source, version_cmd, mode)

    pluginstatus = commands.getstatusoutput(plugin_install_cmd)
    self.assertEquals(0, pluginstatus[0])

    build_cmd = "cca build android"
    buildstatus = commands.getstatusoutput(build_cmd)
    self.assertEquals(0, buildstatus[0])
    os.chdir(
        os.path.join(
            tool_path,
            appname,
            "platforms",
            "android",
            "build",
            "outputs",
            "apk"))
    result = commands.getstatusoutput("ls")
    self.assertIn(".apk", result[1])
    print result[1]
    if "android" in result[1]:
        self.assertIn("android", result[1])
    else:
        self.assertIn(appname, result[1])

def build(appname, isDebug, self):
    os.chdir(os.path.join(tool_path, appname))
    print "Build project %s ----------------> START" % appname
    if CORDOVA_VERSION == "4.x":
        cmd = "cordova build android"
        if isDebug == True:
            print "build debug app"
            cmd = "cordova build android --debug"
    else:
        cmd = "./cordova/build"
        if isDebug == True:
            print "build debug app"
            cmd = "./cordova/build --debug"
    print cmd
    buildstatus = commands.getstatusoutput(cmd)