package com.qmai.android.plugin

import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project

/***
 * 编译加上传到oss中
 */
class OssAndPygerPlugin implements Plugin<Project> {
    @Override
    void apply(Project project) {
        MultiUploadBean ossUploadFileBean = project.getExtensions().create("uploadOssAndPyger", MultiUploadBean.class)
        PygerBean pygerBean = project.getExtensions().create("BuildAndPygerInfo", PygerBean.class)
        project.afterEvaluate {
            Map<String, String> params = System.getenv()
            String type = params.getOrDefault("build_type", "release")
            String flavor = params.getOrDefault("abi_flter", "") // 如果没有取到值，不设置默认值
            type = firstLetterLower(type)
            String dirName = "${project.layout.buildDirectory.asFile.get()}/outputs/apk/"
            String apkName = ossUploadFileBean.apkName
            if (flavor != null && !flavor.isEmpty()) {
                flavor = firstLetterLower(flavor)
                dirName += "$flavor/"
                apkName += "_$flavor"
            }
            dirName += "$type/"
            apkName += "_${type}_${ossUploadFileBean.versionCode}_${ossUploadFileBean.versionName}.apk"
            def uploadFile = new File(dirName + apkName)
            print("-OssAndPygerPlugin--dirName apkName:${dirName + apkName}")
            project.getTasks().register("uploadApkOss", OssUploadTask.class, uploadFile, ossUploadFileBean.ossPath, type,
                    flavor, ossUploadFileBean.appName)
            project.getTasks().register("uploadApkPyger",
                    PygerUploadTask.class, uploadFile,
                    type, pygerBean.key, flavor, ossUploadFileBean.appName)
        }

    };

    String firstLetterLower(String str) {
        if (str == null || str.isEmpty()) {
            return str; // 处理空字符串或 null 的情况
        }
        char[] cs = str.toCharArray();
        if (Character.isUpperCase(cs[0])) {
            cs[0] += 32; // 将首字母转换为小写
        }
        return String.valueOf(cs);
    }
}
