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

/***
 * 编译加上传到pyger中
 */
class PygerBuildAndUploadPlugin implements Plugin<Project> {
    @Override
    void apply(Project project) {
        PygerBean pygerBean = project.getExtensions().create("BuildAndPygerInfo", PygerBean.class)
        project.afterEvaluate {
            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) {
                            def task = project.getTasks().create("BuildAndPyger" + firstLetterUpper(taskName),
                                    PygerUploadTask.class, baseVariantOutput.getOutputFile(),
                                    firstLetterUpper(buildType), pygerBean.key,flavor,appName)
                            //先编译
                            task.dependsOn("assemble" + firstLetterUpper(taskName))
                        }
                    })
                }
            })

        }

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