/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

def EMBEDDED_MODE = "embedded"
def SHARED_MODE = "shared"
def DEFAULT_GROUP_ID = "org.xwalk:"
def SHARED_ARTIFACT_ID = "xwalk_shared_library:"
def EMBEDD_ARTIFACT_ID = "xwalk_core_library:"
def BIT_64 = ":64bit@aar"

repositories {
  maven {
    url 'https://download.01.org/crosswalk/releases/crosswalk/android/maven2'
  }
}

def getConfigPreference(name) {
    name = name.toLowerCase()
    def xml = file("res/xml/config.xml").getText()
    // Disable namespace awareness since Cordova doesn't use them properly
    def root = new XmlParser(false, false).parseText(xml)

    def ret, defaultValue
    root.preference.each { it ->
        def attrName = it.attribute("name")
        if (attrName && attrName.toLowerCase() == name) {
            if (it.attribute('default') != null) {
                defaultValue = it.attribute('default');
            } else {
                ret = it.attribute("value")
            }
        }
    }
    return ret ? ret : defaultValue
}

if (!project.hasProperty('xwalk64bit')) {
    ext.xwalk64bit = getConfigPreference("xwalk64bit");
    println xwalk64bit
}
if (cdvBuildMultipleApks == null) {
    ext.xwalkMultipleApk = getConfigPreference("xwalkMultipleApk").toBoolean();
}

if (cdvMinSdkVersion == null) {
    def minSdk = getConfigPreference("android-minSdkVersion");
    ext.cdvMinSdkVersion =  minSdk && minSdk.toInteger() > 14 ? minSdk : 14;
}

if (!project.hasProperty('xwalkMode')) {
    def mode = getConfigPreference("xwalkMode")
    println mode
    ext.artifactid = mode == SHARED_MODE ? SHARED_ARTIFACT_ID : EMBEDD_ARTIFACT_ID;
}
if (artifactid == SHARED_ARTIFACT_ID) {
    // Build one apk at shared mode because the value of
    // ext.cdvBuildMultipleApks is false by default.
    xwalk64bit = null;
} else if (xwalk64bit == null) {
    // Build embedded 32 bit crosswalk will generate two apks by default.
    ext.cdvBuildMultipleApks = xwalkMultipleApk;
}

// Set defaults before project's build-extras.gradle
if (!project.hasProperty('xwalkVersion')) {
    ext.xwalkVersion = getConfigPreference("xwalkVersion")
}

if (!project.hasProperty('xwalkCommandLine')) {
    ext.xwalkCommandLine = getConfigPreference("xwalkCommandLine")
}
// Apply values after project's build-extras.gradle
cdvPluginPostBuildExtras.add({
    android {
        if (xwalk64bit != null) {
            productFlavors {
                x86_64 {
                    versionCode defaultConfig.versionCode + 6
                    ndk {
                       abiFilters "x86_64", ""
                    }
                }
                arm64 {
                    versionCode defaultConfig.versionCode + 9
                    ndk {
                        abiFilters "arm64-v8a", ""
                    }
                }
            }
        }
    }

    def xwalkSpec = xwalkVersion
    if ((xwalkSpec =~ /:/).count == 1) {
        xwalkSpec = DEFAULT_GROUP_ID + xwalkSpec
    } else if ((xwalkSpec =~ /:/).count == 0) {
        if (xwalkSpec ==~ /\d+/) {
            xwalkSpec = "${xwalkSpec}+"
        }
        xwalkSpec = DEFAULT_GROUP_ID + artifactid + xwalkSpec
    }
    if (xwalk64bit != null) {
        xwalkSpec = xwalkSpec + BIT_64
    }
    println xwalkSpec

    dependencies {
        compile xwalkSpec
    }

    if (file('assets/xwalk-command-line').exists()) {
        println('Not writing assets/xwalk-command-line since file already exists.')
        return
    }
    android.applicationVariants.all { variant ->
        def variantName = variant.name.capitalize()
        def mergeTask = tasks["merge${variantName}Assets"]
        def processTask = tasks["process${variantName}Resources"]
        def outFile = new File (mergeTask.outputDir, "xwalk-command-line")
        def newTask = project.task("createXwalkCommandLineFile${variantName}") << {
            mergeTask.outputDir.mkdirs()
            outFile.write("xwalk ${xwalkCommandLine}\n")
        }
        newTask.dependsOn(mergeTask)
        processTask.dependsOn(newTask)
    }
})
