package com.qmai.android.plugin

import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.ApplicationVariant
import com.android.build.gradle.api.BaseVariantOutput
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project

/***
 * 编译加上传到oss中
 */
class OssBuildAndUploadPlugin implements Plugin<Project> {
    @Override
    void apply(Project project) {

        OssBean ossBean = project.getExtensions().create("BuildAndOssInfo", OssBean.class)
        project.afterEvaluate {
            // AppExtension app = project.
            AppExtension app = project.getExtensions().findByType(AppExtension.class)
            app.getApplicationVariants().all(new Action<ApplicationVariant>() {
                @Override
                void execute(ApplicationVariant applicationVariant) {
                    def taskName = applicationVariant.getName()
                    def buildType = applicationVariant.buildType.name
                    def flavor = applicationVariant.flavorName.isEmpty() ? "未配置" : applicationVariant.flavorName
                    def appName = applicationVariant.buildType.manifestPlaceholders.get("app_name", "企迈数店").toString()
                    applicationVariant.outputs.all(new Action<BaseVariantOutput>() {
                        @Override
                        void execute(BaseVariantOutput baseVariantOutput) {
                            File flie = baseVariantOutput.getOutputFile()
                            def task = project.getTasks().create("buildAndOss" + firstLetterUpper(taskName),
                                    OssUploadTask.class, flie, ossBean.ossPath, firstLetterUpper(buildType), flavor, appName)
                            //先编译
                            // task.dependsOn("clean")
                            task.dependsOn("assemble" + firstLetterUpper(taskName))
                        }
                    })
                }
            })

        }

    };
    //首字符大写
    String firstLetterUpper(String str) {
        char[] cs = str.toCharArray()
        cs[0] -= 32
        return String.valueOf(cs)
    }
}
