package com.qmai.android.plugin.jg

import org.gradle.api.Plugin
import org.gradle.api.Project
import com.android.build.gradle.AppExtension

open class JiaGuPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        //读取360加固配置
        val jiaGuPluginExtension = project.extensions
                .create("jiagu", JiaGuPluginExtension::class.java)
        project.afterEvaluate {
            val appExtension: AppExtension = project.extensions.getByType(AppExtension::class.java) as AppExtension
            appExtension.applicationVariants.all {
                val name = it.name
                it.outputs.all {
                    val outputFile = it.outputFile
                    val jiaGuName = "jiagu-${firstLetterUpper(it.name)}"
                    val jiaGuTask = project.tasks.create(
                            jiaGuName,
                            JiaGuTask::class.java,
                            outputFile,
                            jiaGuPluginExtension
                    )
                    val buildAndJiaGuName = "build-and-$jiaGuName"
                    println("create task:$buildAndJiaGuName")
                    val buildAndJiaGuTask = project.tasks.create(
                            buildAndJiaGuName,
                            JiaGuTask::class.java,
                            outputFile,
                            jiaGuPluginExtension
                    )
                    buildAndJiaGuTask.doFirst {
                        println("${it.name} doFirst")
                    }
                    buildAndJiaGuTask.doLast {
                        println("${it.name} doLast")
                    }
                    buildAndJiaGuTask.dependsOn("assemble${firstLetterUpper(name)}")
                }


            }
        }
    }

    //首字符大写
    fun firstLetterUpper(str: String): String {
        val cs: CharArray = str.toCharArray()
        var first = cs[0]
        //first = (-32).toChar()

        cs[0] = first.toUpperCase()
        return String(cs)
    }
}