using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
#if UNITY_ANDROID
#elif UNITY_IOS
using UnityEditor.iOS.Xcode;
using UnityEditor.iOS.Xcode.Extensions;
using Facebook.Unity.Settings;
#endif
using UnityEngine;

public static class AutoBuild
{
    static void Common(BuildTargetGroup _btg, BuildTarget _bt)
    {
        PlayerSettings.applicationIdentifier = "com.fgb.randomgfgostop";
        EditorUserBuildSettings.SwitchActiveBuildTarget(_btg, _bt);

        if (_bt == BuildTarget.Android)
        {
            PlayerSettings.Android.splitApplicationBinary = false;
            File.WriteAllText("Assets/Resources/VersionCode.txt", PlayerSettings.Android.bundleVersionCode.ToString());
            PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7 | AndroidArchitecture.ARM64;
        }
        else
        {
            File.WriteAllText("Assets/Resources/VersionCode.txt", PlayerSettings.iOS.buildNumber);
            PlayerSettings.iOS.appleDeveloperTeamID = "788PYWMPC6"; // 필굿밴디츠
            //PlayerSettings.iOS.appleDeveloperTeamID = "A9997B8HR5"; // 나인탭
            PlayerSettings.iOS.appleEnableAutomaticSigning = true;
            PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
        }

        EditorUserBuildSettings.SwitchActiveBuildTargetAsync(_btg, _bt);
    }

    static void Show_BuildFolder(BuildTarget _bt)
    {
        if (_bt == BuildTarget.Android) System.Diagnostics.Process.Start("AndroidData");
        else System.Diagnostics.Process.Start("IOSData");
    }
    static void BuildStart(string path, BuildTarget _bt)
    {
        BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, path, _bt, BuildOptions.None);
        Show_BuildFolder(_bt);
    }
#if UNITY_ANDROID
    [MenuItem("AutoBuild/EmptySymbol")]
    static void EmptySymbol()
    {
        PlayerSettings.SetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.Android, "");
    }
    [MenuItem("AutoBuild/Set_AndroidKeyStore")]
    static void Set_AndroidKeyStore()
    {
        PlayerSettings.Android.useCustomKeystore = true;
        PlayerSettings.Android.keystoreName = "AndroidData/RandomGFGoStop.keystore";
        PlayerSettings.Android.keyaliasName = "fgb";
        PlayerSettings.Android.keystorePass = PlayerSettings.Android.keyaliasPass = "fgb123!!";
    }
    [MenuItem("AutoBuild/Set_OneStoreKeyStore")]
    static void Set_OneStoreKeyStore()
    {
        PlayerSettings.Android.useCustomKeystore = true;
        PlayerSettings.Android.keystoreName = "AndroidData/RandomGFGoStop_One.keystore";
        PlayerSettings.Android.keyaliasName = "fgb";
        PlayerSettings.Android.keystorePass = PlayerSettings.Android.keyaliasPass = "fgb123!!";
    }
    [MenuItem("AutoBuild/Build APK with KeyStore")]
    static void Build_APK_with_KeyStore()
    {
        Common(BuildTargetGroup.Android, BuildTarget.Android);
        Set_AndroidKeyStore();
        //PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel23;

        var curVer = PlayerSettings.bundleVersion;
        PlayerSettings.bundleVersion = "9.9.9";
        EditorUserBuildSettings.buildAppBundle = false;
        BuildStart("AndroidData/GoStop_Test_" + Application.version + "_(" + PlayerSettings.Android.bundleVersionCode + ").apk", BuildTarget.Android);
        PlayerSettings.bundleVersion = curVer;
    }
    [MenuItem("AutoBuild/Build APK with KeyStore (OneStore)")]
    static void Build_APK_OneStore()
    {
        Common(BuildTargetGroup.Android, BuildTarget.Android);
        Set_OneStoreKeyStore();
        //PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel23;

        PlayerSettings.SetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.Android, "OneStore");
        EditorUserBuildSettings.buildAppBundle = false;
        BuildStart("AndroidData/GoStop_Test_" + Application.version + "_(" + PlayerSettings.Android.bundleVersionCode + ").apk", BuildTarget.Android);
        EmptySymbol();
    }
    [MenuItem("AutoBuild/Build Live AAB")]
    static void Build_AAB()
    {
        ++PlayerSettings.Android.bundleVersionCode;
        Common(BuildTargetGroup.Android, BuildTarget.Android);
        Set_AndroidKeyStore();

        PlayerSettings.SetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.Android, "");
        EditorUserBuildSettings.buildAppBundle = true;
        BuildStart("AndroidData/GoStop_Live_" + Application.version + "_(" + PlayerSettings.Android.bundleVersionCode + ").aab", BuildTarget.Android);
        EmptySymbol();
        //if (EditorUtility.DisplayDialog("라이브 빌드", "현재 버전 : " + PlayerSettings.bundleVersion + "  " + PlayerSettings.Android.bundleVersionCode.ToString(), "OK", "Not Build"))
        //    AppBundlePublisher.Build();
    }
    [MenuItem("AutoBuild/Build Live AAB (OneStore)")]
    static void Build_AAB_OneStore()
    {
        ++PlayerSettings.Android.bundleVersionCode;
        Common(BuildTargetGroup.Android, BuildTarget.Android);
        Set_OneStoreKeyStore();

        PlayerSettings.SetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.Android, "");
        EditorUserBuildSettings.buildAppBundle = true;
        BuildStart("AndroidData/GoStop_Live_OneStore" + Application.version + "_(" + PlayerSettings.Android.bundleVersionCode + ").aab", BuildTarget.Android);
        EmptySymbol();
        //if (EditorUtility.DisplayDialog("라이브 빌드", "현재 버전 : " + PlayerSettings.bundleVersion + "  " + PlayerSettings.Android.bundleVersionCode.ToString(), "OK", "Not Build"))
        //    AppBundlePublisher.Build();
    }
#endif
#if UNITY_IOS
    [MenuItem("AutoBuild/IOS Xcode")]
    static void Build_IOS_Xcode()
    {
        PlayerSettings.iOS.buildNumber = (int.Parse(PlayerSettings.iOS.buildNumber) + 1).ToString();
        PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, "FGB_LIVE");
        Common(BuildTargetGroup.iOS, BuildTarget.iOS);

        BuildStart("IOSData/IOSXcodeLive_" + Application.version + "_" + PlayerSettings.iOS.buildNumber, BuildTarget.iOS);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, "");
    }
    [MenuItem("AutoBuild/IOS Xcode Test")]
    static void Build_IOS_Xcode_Test()
    {
        PlayerSettings.iOS.buildNumber = (int.Parse(PlayerSettings.iOS.buildNumber) + 1).ToString();
        Common(BuildTargetGroup.iOS, BuildTarget.iOS);

        BuildStart("IOSData/IOSSRDebugOn_" + Application.version + "_" + PlayerSettings.iOS.buildNumber, BuildTarget.iOS);
    }
    [MenuItem("AutoBuild/Test IOS Simulator")]
    static void Build_Test_IOS_Simulator()
    {
        Common(BuildTargetGroup.iOS, BuildTarget.iOS);
        PlayerSettings.iOS.sdkVersion = iOSSdkVersion.SimulatorSDK;

        BuildStart("IOSData/IOSTestBuild_" + Application.version + "_" + PlayerSettings.iOS.buildNumber, BuildTarget.iOS);
    }
#endif

    [PostProcessBuild(1)]
    static void OnPostProcessBuild(BuildTarget buildTarget, string path)
    {
        if (buildTarget == BuildTarget.iOS)
        {
#if UNITY_IOS
            Debug.Log("OnPostProcessBuild : " + path);

            var plistPath = Path.Combine(path, "Info.plist");
            var plist = new PlistDocument();
            plist.ReadFromFile(plistPath);

            PlistElementDict allowsDict = plist.root.CreateDict("NSAppTransportSecurity");
			allowsDict.SetBoolean("NSAllowsArbitraryLoads", true);
			PlistElementDict exceptionsDict = allowsDict.CreateDict("NSExceptionDomains");
			PlistElementDict domainDict = exceptionsDict.CreateDict("amazonaws.com");
			domainDict.SetBoolean("NSExceptionAllowsInsecureHTTPLoads", true);
			domainDict.SetBoolean("NSIncludesSubdomains", true);
            domainDict = exceptionsDict.CreateDict("inonotebook.iptime.org");
			domainDict.SetBoolean("NSExceptionAllowsInsecureHTTPLoads", true);
			domainDict.SetBoolean("NSIncludesSubdomains", true);

            plist.root.SetBoolean("GADIsAdManagerApp", true);
            plist.root.SetBoolean("FirebaseMessagingAutoInitEnabled", false);
            plist.root.SetBoolean("FirebaseAppStoreReceiptURLCheckEnabled", false);
            plist.root.SetBoolean("ITSAppUsesNonExemptEncryption", false);
            plist.root.SetString("NSAdvertisingAttributionReportEndpoint", "https://appsflyer-skadnetwork.com/");

            // Add string setting
            // SKAdNetwork IDs integration(for iOS14+)
            var arraySKAdNetworkItems = plist.root.CreateArray("SKAdNetworkItems");
            foreach (string id in SKAdNetworkIdentifiers)
            {
                var dict = arraySKAdNetworkItems.AddDict();
                dict.SetString("SKAdNetworkIdentifier", id);
            }

            plist.root.SetString("FacebookAppID", FacebookSettings.AppId);
            plist.root.SetString("FacebookDisplayName", Application.productName);
            // Add URL Scheme
            var array = plist.root.CreateArray("CFBundleURLTypes");
            var urlDict = array.AddDict();
            urlDict.SetString("CFBundleURLName", Application.identifier);
            var urlInnerArray = urlDict.CreateArray("CFBundleURLSchemes");
            urlInnerArray.AddString("fb" + FacebookSettings.AppId);
            var googleiosurlscheme = urlDict.CreateArray("CFBundleURLSchemes");
            googleiosurlscheme.AddString("com.googleusercontent.apps.107333004578-n74n1eaap2bgtg2od6ia1vk4ls5c139j");

            var fbArray = plist.root.CreateArray("LSApplicationQueriesSchemes");
            fbArray.AddString("fbapi");
            fbArray.AddString("fb-messenger-api");
            fbArray.AddString("fbauth2");
            fbArray.AddString("fbshareextension");

            plist.WriteToFile(plistPath);

            // get project info
            string pbxPath = PBXProject.GetPBXProjectPath(path);
            var proj = new PBXProject();
            proj.ReadFromFile(pbxPath);
            var guid = proj.GetUnityMainTargetGuid();
            var unitytest = proj.TargetGuidByName(PBXProject.GetUnityTestTargetName());
            var unityframework = proj.GetUnityFrameworkTargetGuid();

            proj.AddBuildProperty(guid, "OTHER_LDFLAGS", "-lc++");
            proj.SetBuildProperty(guid, "ENABLE_BITCODE", "NO");
            proj.SetBuildProperty(guid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
            proj.SetBuildProperty(unitytest, "ENABLE_BITCODE", "NO");
            proj.SetBuildProperty(unityframework, "ENABLE_BITCODE", "NO");
            proj.SetBuildProperty(unityframework, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "NO");

            // Add Push framework
            proj.AddFrameworkToProject(guid, "UserNotifications.framework", false);

            proj.WriteToFile(pbxPath);

            // get entitlements path
            string[] idArray = Application.identifier.Split('.');
            var entitlementsPath = $"Unity-iPhone/{idArray[idArray.Length - 1]}.entitlements";

            // create capabilities manager
            var capManager = new ProjectCapabilityManager(pbxPath, entitlementsPath, null, guid);

            // Add necessary capabilities
            capManager.AddPushNotifications(true);
            capManager.AddSignInWithApple();
            capManager.AddBackgroundModes(BackgroundModesOptions.RemoteNotifications);

            // Write to file
            capManager.WriteToFile();

            Debug.Log("OnPostProcessBuild end");
#endif
        }
    }
    [PostProcessBuild(45)]//must be between 40 and 50 to ensure that it's not overriden by Podfile generation (40) and that it's added before "pod install" (50)
    public static void FixPodFile(BuildTarget buildTarget, string buildPath)
    {
        if (buildTarget != BuildTarget.iOS)
        {
            return;
        }
        Debug.Log("FixPodFile");
        using (StreamWriter sw = File.AppendText(buildPath + "/Podfile"))
        {
            sw.WriteLine("post_install do |installer|");
            sw.WriteLine("installer.generated_projects.each do |project|");
            sw.WriteLine("project.targets.each do |target|");
            sw.WriteLine("target.build_configurations.each do |config|");
            sw.WriteLine("config.build_settings[\"DEVELOPMENT_TEAM\"] = \"788PYWMPC6\"");
            sw.WriteLine("end\nend\nend\nend");
        }

        //string podfilePath = Path.Combine(buildPath, "Podfile");
        //if (File.Exists(podfilePath))
        //{
        //    string[] lines = File.ReadAllLines(podfilePath);
        //    for (int i = 0; i < lines.Length; i++)
        //    {
        //        if (lines[i].Contains("Firebase/Auth"))
        //            lines[i] = "  pod 'Firebase/Auth', '10.28.1'";
        //        else if (lines[i].Contains("GoogleSignIn"))
        //            lines[i] = "  pod 'GoogleSignIn', '5.0.0'";
        //        else if (lines[i].Contains("GTMSessionFetcher/Core'"))
        //            lines[i] = "  pod 'GTMSessionFetcher/Core'', '2.1'";
        //    }
        //    File.WriteAllLines(podfilePath, lines);
        //}
    }

    private static readonly string[] SKAdNetworkIdentifiers = new string[]
    {
        "v9wttpbfk9.skadnetwork",
        "n38lu8286q.skadnetwork",
        "su67r6k2v3.skadnetwork",
        "9t245vhmpl.skadnetwork",
        "m8dbw4sv7c.skadnetwork",
        "tl55sbb4fm.skadnetwork",
        "wzmmz9fp6w.skadnetwork",
        "4fzdc2evr5.skadnetwork",
        "294l99pt4k.skadnetwork",
        "4w7y6s5ca2.skadnetwork",
        "7ug5zh24hu.skadnetwork",
        "5l3tpt7t6e.skadnetwork",
        "t38b2kh725.skadnetwork",
        "c6k4g5qg8m.skadnetwork",
        "wg4vff78zm.skadnetwork",
        "v72qych5uu.skadnetwork",
        "mp6xlyr22a.skadnetwork",
        "cstr6suwn9.skadnetwork",
        "4pfyvq9l8r.skadnetwork",
        "w9q455wk68.skadnetwork",
        "44jx6755aq.skadnetwork",
        "k6y4y55b64.skadnetwork",
        "8s468mfl3y.skadnetwork",
        "mlmmfzh3r3.skadnetwork",
        "4dzt52r2t5.skadnetwork",
        "ydx93a7ass.skadnetwork",
        "3qy4746246.skadnetwork",
        "prcb7njmu6.skadnetwork",
        "v79kvwwj4g.skadnetwork",
        "glqzh8vgby.skadnetwork",
        "s39g8k73mm.skadnetwork",
        "238da6jt44.skadnetwork",
        "424m5254lk.skadnetwork",
        "5a6flpkh64.skadnetwork",
        "hs6bdukanm.skadnetwork",
        "x44k69ngh6.skadnetwork",
        "a8cz6cu7e5.skadnetwork",
        "488r3q3dtq.skadnetwork",
        "32z4fx6l9h.skadnetwork",
        "22mmun2rn5.skadnetwork",
        "3rd42ekr43.skadnetwork",
        "6yxyv74ff7.skadnetwork",
        "ppxm28t8ap.skadnetwork",
        "lr83yxwka7.skadnetwork",
        "578prtvx9j.skadnetwork",
        "a2p9lx4jpn.skadnetwork",
        "av6w8kgt66.skadnetwork",
        "4468km3ulz.skadnetwork",
        "9rd848q2bz.skadnetwork",
        "5lm9lj6jb7.skadnetwork",
        "f7s53z58qe.skadnetwork",
        "k674qkevps.skadnetwork",
        "kbd757ywx3.skadnetwork",
        "yclnxrl5pm.skadnetwork",
        "zq492l623r.skadnetwork",
        "zmvfpc5aq8.skadnetwork",
        "f73kdq92p3.skadnetwork",
        "f38h382jlk.skadnetwork",
        "2u9pt9hc89.skadnetwork",
        "5tjdwbrq8w.skadnetwork",
        "3sh42y64q3.skadnetwork",
        "9nlqeag3gk.skadnetwork"
    };
}