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.get("abi_flter") // 如果没有取到值，不设置默认值

            type = firstLetterLower(type)

            String dirName = "${project.layout.buildDirectory.asFile.get()}/outputs/apk/"
            if (flavor != null) {
                dirName += "$flavor/"
            }
            dirName += "$type/"

            File apkDir = new File(dirName)

            // 查找 .apk 文件
            def apkFiles = project.fileTree(dir: dirName, include: '**/*.apk').files
            apkFiles(new FileFilter() {
                @Override
                boolean accept(File pathname) {
                    return pathname.endsWith(".apk")
                }
            })


            if (apkFiles == null || apkFiles.length == 0) {
                throw new GradleException("No APK found in directory: " + dirName)
            }

            File uploadFile = apkFiles[0] // 可按需排序选择最新的或唯一的

            println("-OssAndPygerPlugin--found apk: ${uploadFile.getAbsolutePath()}")

            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);
    }
}
