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

class BuildGradleProcessor4x
{
    private string launcherBuildGradle;
    private string unityLibraryBuildGradle;
    private string rootBuildGradle;

    public BuildGradleProcessor4x(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");
        Debug.Log("BuildGradleProcessor, rootProjectPath:" + rootProjectPath + "\n,launcherBuildGradle:"
        + launcherBuildGradle + "\n,unityLibraryBuildGradle:" + unityLibraryBuildGradle);
    }

    public void process()
    {
        Debug.Log("BuildGradleProcessor4x, process start....");
        //1. 添加maven仓库
        processMaven();

        //3. 添加插件 ，apply + classpath + json文件 + 打包设置
        processPlugin();
        Debug.Log("BuildGradleProcessor4x, process end....");
    }

    private void processMaven()
    {
        string buildGradleContent = File.ReadAllText(rootBuildGradle);
        List<string> pluginMaven = new List<string>();
        buildGradleContent = insertMaven(pluginMaven, buildGradleContent);
        pluginMaven.Add("http://sdkck.tuyoo.com/artifactory/tuyoo-component/");
        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(rootBuildGradle, 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()
    {    
        //root build gradle 处理
        string rootBuildGradleContent = File.ReadAllText(rootBuildGradle);
        if (!rootBuildGradleContent.Contains("com.tuyoo.sdk_plugin"))
        {
            rootBuildGradleContent = rootBuildGradleContent.Replace("dependencies {", @"dependencies {
                classpath 'com.tuyoo.sdk_plugin:com.tuyoo.sdk_plugin.gradle.plugin:1.7.6.4'");
            File.WriteAllText(rootBuildGradle, rootBuildGradleContent);
        }

        //launcher build gradle 处理
        string launcherBuildGradleContent = File.ReadAllText(launcherBuildGradle);
        // 正则表达式：匹配 #START1 到 #END1 之间的所有内容（包括换行）
        string pattern = @"//START1[\s\S]*?//END1";
        //             string replaceMent = @"import groovy.json.JsonSlurper
        // // File tyConfigFileDir = project.rootProject.file('config')
        // // File tyConfigFile = new File(tyConfigFileDir,'build.json')
        // // // 使用 JsonSlurper 解析 JSON
        // // def jsonSlurper = new JsonSlurper()
        // // def jsonObject = jsonSlurper.parseText(tyConfigFile.text)
        // buildscript {
        //     repositories {
        //         google {
        //             content {
        //                 includeGroupByRegex(""com\\.android.*"")
        //                 includeGroupByRegex(""com\\.google.*"")
        //                 includeGroupByRegex(""androidx.*"")
        //             }
        //         }
        //         mavenCentral()
        //         gradlePluginPortal()

        //         // 配置HMS Core SDK的Maven仓地址。
        //         maven { url 'https://developer.huawei.com/repo/' }
        //     }
        //     dependencies {
        //         // 增加Android Gradle插件版本号配置，{version}为实际的Gradle插件版本号，例如7.1.1。
        //         // 增加AGC插件配置，请您参见AGC插件依赖关系选择合适的AGC插件版本。
        //         classpath 'com.huawei.agconnect:agcp:1.9.0.300'

        //         // 增加Android Gradle插件版本号配置，{version}为实际的Gradle插件版本号，例如7.1.1。
        //         classpath 'com.android.tools.build:gradle:7.4.2'
        //     }
        // }
        // apply plugin: 'com.tuyoo.sdk_plugin'";
        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);
        }
    }

}
