
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

class BuildGradleProcessor7x
{
    private string launcherBuildGradle;
    private string unityLibraryBuildGradle;
    private string rootBuildGradle;
    private string settings;

    public BuildGradleProcessor7x(string rootProjectPath)
    {
        this.launcherBuildGradle = Path.Combine(rootProjectPath, "launcher/build.gradle");
        this.unityLibraryBuildGradle = Path.Combine(rootProjectPath, "unityLibrary/build.gradle");
        this.rootBuildGradle = Path.Combine(rootProjectPath, "build.gradle");
        this.settings = Path.Combine(rootProjectPath, "settings.gradle");
        Debug.Log("BuildGradleProcessor, rootProjectPath:" + rootProjectPath + "\n,launcherBuildGradle:"
        + launcherBuildGradle + "\n,unityLibraryBuildGradle:" + unityLibraryBuildGradle + "\n,settings:" + settings);
    }

    public void process()
    {
        //1. 添加maven仓库
        processMaven();

        //3. 添加插件 ，apply + classpath + json文件 + 打包设置
        processPlugin();
    }

    private void processMaven()
    {
        string buildGradleContent = File.ReadAllText(settings);
        List<string> pluginMaven = new List<string>();
        buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
        //pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component/");
        pluginMaven.Add("file:///" + FileUtil.GetPhysicalPath("Packages/com.bywaystudios.tuyoosdk/Editor/Android") + "/.m2/repository");
        pluginMaven.Add("https://jcenter.bintray.com/");
        // pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component-test/");
        pluginMaven.Add("https://developer.huawei.com/repo/");
        buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
        // 保存修改后的内容回文件
        File.WriteAllText(settings, buildGradleContent);
    }

    private string insertMaven(List<string> maven, string buildGradleContent)
    {
        if (maven == null)
        {
            return buildGradleContent;
        }
        // 添加自定义的 Maven 仓库
        foreach (string url in maven)
        {
            if (!buildGradleContent.Contains(url))
            {
                string mavenRepository = buildMavenString(url);
                Debug.Log("mavenRepository: " + mavenRepository);

                // 在 repositories 块中添加自定义仓库
                buildGradleContent = buildGradleContent.Replace("repositories {", $"repositories {{\n{mavenRepository}");
            }
        }

        return buildGradleContent;
    }

    string buildMavenString(string url)
    {
        string mavenString = "";
        mavenString += $@"
                    maven {{
                        allowInsecureProtocol = true
                        url '{url}'
                    }}";
        return mavenString;
    }


    private void processPlugin()
    {
        string projectPluginVersion = "1.7.6.4";
        string firebasePluginVersion = "4.3.15"; // AGP 7.x 适合用4.3.15版本， AGP 8.x 适合用4.4.x版本
        string crashPluginVersion = "2.9.5"; //支持AGP8以下
        // string crashPluginVersion = "3.0.2"; //支持AGP8
    
        //root build gradle 处理
        string rootBuildGradleContent = File.ReadAllText(rootBuildGradle);
        if (!rootBuildGradleContent.Contains("com.tuyoo.sdk_plugin"))
        {

            rootBuildGradleContent = rootBuildGradleContent.Replace("plugins {", @"plugins {
        id 'com.tuyoo.sdk_plugin' version '" + projectPluginVersion + @"' apply false
        id 'com.google.gms.google-services' version '" + firebasePluginVersion + @"' apply false;
        id 'com.google.firebase.crashlytics' version '" + crashPluginVersion + @"' apply false");
            File.WriteAllText(rootBuildGradle, rootBuildGradleContent);
        }

        //launcher build gradle 处理
        string launcherBuildGradleContent = File.ReadAllText(launcherBuildGradle);
        // 正则表达式：匹配 #START1 到 #END1 之间的所有内容（包括换行）
        string pattern = @"//START1[\s\S]*?//END1";
        string replaceMent = @"
apply plugin: 'com.tuyoo.sdk_plugin'";
        string insertContent = $"//START1\n{replaceMent}\n//END1";
        // 执行替换
        string tmp = Regex.Replace(launcherBuildGradleContent, pattern, insertContent);
        if (tmp.Equals(launcherBuildGradleContent))
        {
            if (!tmp.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
            {
                launcherBuildGradleContent = launcherBuildGradleContent + "\n" + insertContent;
            }
        }
        else
        {
            launcherBuildGradleContent = tmp;
        }
        File.WriteAllText(launcherBuildGradle, launcherBuildGradleContent);

        //unity build gradle 处理
        string unityBuildGradleContent = File.ReadAllText(unityLibraryBuildGradle);
        if (!unityBuildGradleContent.Contains("apply plugin: 'com.tuyoo.sdk_plugin'"))
        {
            unityBuildGradleContent = unityBuildGradleContent + "\n" + "apply plugin: 'com.tuyoo.sdk_plugin'";
            File.WriteAllText(unityLibraryBuildGradle, unityBuildGradleContent);
        }
    }

}
