
#if UNITY_IOS

using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEditor;
using System.IO;

namespace tysdk.editor
{

    public class iOSPostBuildProcessor
    {
        [PostProcessBuild(1000)]
        public static void ChangeXcodeSettings(BuildTarget buildTarget, string pathToBuiltProject)
        {
            if (buildTarget == BuildTarget.iOS)
            {
                UnityEngine.Debug.Log($"ChangeXcodeSettings {pathToBuiltProject}");
                ProcessXCodeProj(pathToBuiltProject);
            }
        }

        private static void ProcessXCodeProj(string pathToBuiltProject)
        {
            string pbxprojPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
            PBXProject proj = new PBXProject();
            proj.ReadFromFile(pbxprojPath);

            string target = proj.GetUnityMainTargetGuid();
            XCodeSetSigingAndCapbilities(target, proj, pathToBuiltProject);
            ProcessBuildSettings(proj);
            XcodeOverwriteFiles(pathToBuiltProject, proj);

            UnityEngine.Debug.Log($"XCodeProj {pbxprojPath}");
            File.WriteAllText(pbxprojPath, proj.WriteToString());

            ProcessPlist(pathToBuiltProject);

        }

        private static void XcodeOverwriteFiles(string projPath, PBXProject proj)
        {

            string mainAppPath = Path.Combine(projPath, "MainApp", "main.mm");
            string mainContent = File.ReadAllText(mainAppPath);
            string newContent = mainContent.Replace("#include <UnityFramework/UnityFramework.h>", @"#include ""../UnityFramework/UnityFramework.h""");
            File.WriteAllText(mainAppPath, newContent);
            
            mainAppPath = Path.Combine(projPath, "Classes", "Preprocessor.h");
            mainContent = File.ReadAllText(mainAppPath);
            newContent = mainContent.Replace("#define UNITY_USES_REMOTE_NOTIFICATIONS 0", "#define UNITY_USES_REMOTE_NOTIFICATIONS 1");
            File.WriteAllText(mainAppPath, newContent);
        }

        private static void XCodeSetSigingAndCapbilities(string target, PBXProject proj, string root)
        {
            var entitlementsContent = File.ReadAllText("Packages/tysdk/Files/Unity-iPhone.entitlements");
            File.WriteAllText($"{root}/Unity-iPhone/Unity-iPhone.entitlements", entitlementsContent);

            proj.AddCapability(target, PBXCapabilityType.SignInWithApple, "Unity-iPhone/Unity-iPhone.entitlements");
            proj.AddCapability(target, PBXCapabilityType.KeychainSharing, "Unity-iPhone/Unity-iPhone.entitlements");
            proj.AddCapability(target, PBXCapabilityType.PushNotifications, "Unity-iPhone/Unity-iPhone.entitlements");
            //proj.AddCapability(target, PBXCapabilityType.AssociatedDomains, "Unity-iPhone/Unity-iPhone.entitlements");
        }

        private static void ProcessBuildSettings(PBXProject proj)
        {
            string target = proj.TargetGuidByName("GameAssembly");
            proj.AddBuildProperty(target, "OTHER_LDFLAGS", "-all_load");

            target = proj.TargetGuidByName("UnityFramework");
            proj.SetBuildProperty(target, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "NO");
            proj.AddBuildProperty(target, "OTHER_LDFLAGS", "-ObjC");
            proj.AddFrameworkToProject(target, "AppTrackingTransparency.framework", false);

            proj.AddFrameworkToProject(target,"StoreKit.framework", false);
            proj.AddFrameworkToProject(target,"CFNetwork.framework", false);
            proj.AddFrameworkToProject(target,"CoreTelephony.framework", false);
            proj.AddFrameworkToProject(target,"Security.framework", false);
            proj.AddFrameworkToProject(target,"SystemConfiguration.framework", false);
            proj.AddFrameworkToProject(target,"libc++.tbd", false);
            proj.AddFrameworkToProject(target,"libsqlite3.tbd", false);
            proj.AddFrameworkToProject(target,"libz.tbd", false);
            proj.AddFrameworkToProject(target,"Accelerate.framework", false);
            proj.AddFrameworkToProject(target,"AuthenticationServices.framework", false);
            proj.AddFrameworkToProject(target,"SafariServices.framework", false);
            proj.AddFrameworkToProject(target,"LocalAuthentication.framework", false);
            proj.AddFrameworkToProject(target,"CoreGraphics.framework", false);
            proj.AddFrameworkToProject(target,"WebKit.framework", false);
        }

        private static void ProcessPlist(string root)
        {
            string plistPath = root + "/Info.plist";
            PlistDocument plist = new PlistDocument();
            plist.ReadFromString(File.ReadAllText(plistPath));
            PlistElementDict infoDict = plist.root;

            PlistElementArray urlTypesArray = null;
            if (!infoDict.values.ContainsKey("CFBundleURLTypes")) {
                urlTypesArray = infoDict.CreateArray("CFBundleURLTypes");
            } else {
                urlTypesArray = infoDict.values["CFBundleURLTypes"].AsArray();
            }

            if (!infoDict.values.ContainsKey("NSUserActivityTypes")) {
                PlistElementArray userActivityTypes = infoDict.CreateArray("NSUserActivityTypes");
                userActivityTypes.AddString("INSendMessageIntent");
            } 
            else
            {
                PlistElementArray userActivityTypes = infoDict.values["NSUserActivityTypes"].AsArray();
                userActivityTypes.AddString("INSendMessageIntent");
            }

            PlistElementArray queriesSchemesArray = null;
            if (!infoDict.values.ContainsKey("LSApplicationQueriesSchemes")) {
                queriesSchemesArray = infoDict.CreateArray("LSApplicationQueriesSchemes");
            } else {
                queriesSchemesArray = infoDict.values["LSApplicationQueriesSchemes"].AsArray();
            }

            // AAT
            var trackingDescription = "Data will be used to deliver personalized content to you";
            infoDict.SetString("NSUserTrackingUsageDescription", trackingDescription);

            // Photo Library
            infoDict.SetBoolean("PHPhotoLibraryPreventAutomaticLimitedAccessAlert", true);
            var photoLibraryUsageDescription = "The app requires your consent to add photos or videos to the photo gallery so that you can manage and share them more easily. We are committed to protecting your privacy and complying with relevant laws and regulations.";
            infoDict.SetString("NSPhotoLibraryUsageDescription", photoLibraryUsageDescription);

            // UIFileSharing
            infoDict.SetBoolean("UIFileSharingEnabled", true);

            // Google
			string googleClientID = "com.googleusercontent.apps.481260393117-88n0v3ht8ashhk0r5ri47hced7o5qj62";
			CreateURLTypes(urlTypesArray.AddDict(), "google", googleClientID);

            //Facebook
            {
                string faceBookAppId = "162066986963808";
                string faceBookDisPlayname = "arkgame";
                string facebookClientToken = "5fe59b0d985ad7acb51f48081e69d45b";
                PlistElementDict facebookDic = urlTypesArray.AddDict();
                PlistElementArray fbSchmes = facebookDic.CreateArray("CFBundleURLSchemes");

                CreateURLTypes(urlTypesArray.AddDict(), "fb", $"fb{faceBookAppId}");

                infoDict.SetString("FacebookAppID", faceBookAppId);
                infoDict.SetString("FacebookDisplayName", faceBookDisPlayname);
                infoDict.SetString("FacebookClientToken", facebookClientToken);
                //白名单
                queriesSchemesArray.AddString("fb-messenger-share-api");
                queriesSchemesArray.AddString("fbauth2");
                queriesSchemesArray.AddString("fbauth");
                queriesSchemesArray.AddString("fbshareextension");
                queriesSchemesArray.AddString("fbapi");
                queriesSchemesArray.AddString("fbapi20130214");
                queriesSchemesArray.AddString("fbapi20130410");
                queriesSchemesArray.AddString("fbapi20130702");
                queriesSchemesArray.AddString("fbapi20131010");
                queriesSchemesArray.AddString("fbapi20131219");
                queriesSchemesArray.AddString("fbapi20140410");
                queriesSchemesArray.AddString("fbapi20140116");
                queriesSchemesArray.AddString("fbapi20150313");
                queriesSchemesArray.AddString("fbapi20150629");
                queriesSchemesArray.AddString("fbapi20160328");
            }

            File.WriteAllText(plistPath, plist.WriteToString());
        }

        private static void CreateURLTypes(PlistElementDict dict, string name, string scheme1) 
        {
            dict.SetString("CFBundleTypeRole", "Editor");
            dict.SetString("CFBundleURLName", name);
            dict.CreateArray("CFBundleURLSchemes");
            PlistElementArray schemes = dict.values["CFBundleURLSchemes"].AsArray();
            schemes.AddString(scheme1);
        }
    }
}

#endif
