using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Stove.StoveSDK;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEditor.iOS.Xcode.Extensions;
using UnityEngine;

public class XcodeSettingsPostProcesser
{
    [PostProcessBuildAttribute(10)]
    public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
    {
        // Stop processing if targe is NOT iOS
        if (buildTarget != BuildTarget.iOS)
            return;

        var instance = StoveSettings.Instance; //:Load

        // Initialize PbxProject
        var projectPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";

        PBXProject pbxProject = new PBXProject();
        pbxProject.ReadFromFile(projectPath);
#if UNITY_2019_3_OR_NEWER
        string targetGuid = pbxProject.GetUnityMainTargetGuid();
        string frameworkTargetGuid = pbxProject.GetUnityFrameworkTargetGuid();
#else
        string targetGuid = pbxProject.TargetGuidByName("Unity-iPhone");
#endif
        // Sample of update build property

        pbxProject.AddBuildProperty(targetGuid, "HEADER_SEARCH_PATHS", "$(inherited)");
        pbxProject.AddBuildProperty(targetGuid, "FRAMEWORK_SEARCH_PATHS", "$(inherited)");
        pbxProject.AddBuildProperty(targetGuid, "OTHER_CFLAGS", "$(inherited)");
        pbxProject.AddBuildProperty(targetGuid, "OTHER_LDFLAGS", "");
        pbxProject.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO");
        pbxProject.SetBuildProperty(targetGuid, "SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD", "NO");
        pbxProject.AddBuildProperty(targetGuid, "LIBRARY_SEARCH_PATHS", "$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)");
        pbxProject.AddBuildProperty(targetGuid, "LIBRARY_SEARCH_PATHS", "$(SDKROOT)/usr/lib/swift");
        pbxProject.AddBuildProperty(targetGuid, "LIBRARY_SEARCH_PATHS", "$(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME)");
        
        pbxProject.SetBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "/usr/lib/swift");
        pbxProject.AddBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "$(inherited)");
        pbxProject.AddBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
        pbxProject.AddBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "@loader_path/Frameworks");
        pbxProject.AddBuildProperty(targetGuid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
        pbxProject.SetBuildProperty(targetGuid, "DEVELOPMENT_TEAM", "YOUR_TEAM_ID");
        if (StoveSettings.EnableGUID)
        {
            if (StoveSettings.EnableVTCO)
            {
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE", "YOUR_APP_PROVISIONING_PROFILE_UUID");
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_APP_PROVISIONING_PROFILE_NAME");
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.guid.vn");
            }
            else
            {
            pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE", "YOUR_APP_PROVISIONING_PROFILE_UUID");
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_APP_PROVISIONING_PROFILE_NAME");
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.guid");
            }
        }
        else
        {
            if (StoveSettings.EnableVTCO)
            {
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE", "YOUR_APP_PROVISIONING_PROFILE_UUID");
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_APP_PROVISIONING_PROFILE_NAME");
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios.vn");
            }
            else
            {
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE", "YOUR_APP_PROVISIONING_PROFILE_UUID");
                pbxProject.SetBuildProperty(targetGuid, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_APP_PROVISIONING_PROFILE_NAME");
                PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.stove.mvp.ios");
            }
        }

#if UNITY_2019_3_OR_NEWER
        pbxProject.SetBuildProperty(frameworkTargetGuid, "ENABLE_BITCODE", "NO");
        pbxProject.SetBuildProperty(frameworkTargetGuid, "SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD", "NO");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LIBRARY_SEARCH_PATHS", "$(SDKROOT)/usr/lib/swift");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LIBRARY_SEARCH_PATHS", "$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LIBRARY_SEARCH_PATHS", "$(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME)");
        pbxProject.SetBuildProperty(frameworkTargetGuid, "LD_RUNPATH_SEARCH_PATHS", "/usr/lib/swift");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LD_RUNPATH_SEARCH_PATHS", "$(inherited)");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "LD_RUNPATH_SEARCH_PATHS", "@loader_path/Frameworks");
        pbxProject.AddBuildProperty(frameworkTargetGuid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "NO");
#else

#endif
        pbxProject.SetBuildProperty(targetGuid, "IPHONEOS_DEPLOYMENT_TARGET", MinimumIOSDeploymentTarget);
#if UNITY_2019_3_OR_NEWER
        pbxProject.SetBuildProperty(frameworkTargetGuid, "IPHONEOS_DEPLOYMENT_TARGET", MinimumIOSDeploymentTarget);
        ConfigureSceneDelegateForSample(
            pbxProject,
            frameworkTargetGuid,
            pathToBuiltProject,
            Application.unityVersion);
#endif
        pbxProject.AddCapability(targetGuid, PBXCapabilityType.GameCenter);
        pbxProject.AddCapability(targetGuid, PBXCapabilityType.PushNotifications, ProjectSettingsEntitlementsFilePath);
        pbxProject.AddCapability(targetGuid, PBXCapabilityType.KeychainSharing, ProjectSettingsEntitlementsFilePath);

        string buildType = StoveSettings.IOSBuildType;
        if (buildType == "adhoc")
        {
            pbxProject.AddCapability(targetGuid, PBXCapabilityType.SignInWithApple);
            pbxProject.AddCapability(targetGuid, PBXCapabilityType.AppGroups, ProjectSettingsEntitlementsFilePath);

            // Add NotificationServiceExtension Target
            var pathToNotificationService = Path.GetFullPath(NotificationServicePath);
            var notificationServicePlistPath = pathToNotificationService + "Info.plist";
            PlistDocument notificationServicePlist = new PlistDocument();
            notificationServicePlist.ReadFromFile(notificationServicePlistPath);
            notificationServicePlist.root.SetString("CFBundleShortVersionString", "1.0");
            notificationServicePlist.root.SetString("CFBundleVersion", PlayerSettings.iOS.buildNumber.ToString());

            string notificationServiceTarget;
            if (StoveSettings.EnableGUID)
            {
                if (StoveSettings.EnableVTCO)
                {
                    notificationServiceTarget = PBXProjectExtensions.AddAppExtension(pbxProject, targetGuid, "NotificationServiceExtension", "com.stove.mvp.ios.guid.vn.notification", notificationServicePlistPath);
                }
                else
                {  
                    notificationServiceTarget = PBXProjectExtensions.AddAppExtension(pbxProject, targetGuid, "NotificationServiceExtension", "com.stove.mvp.ios.guid.notification", notificationServicePlistPath);
                }
            }
            else
            {
                if (StoveSettings.EnableVTCO)
                {
                    notificationServiceTarget = PBXProjectExtensions.AddAppExtension(pbxProject, targetGuid, "NotificationServiceExtension", "com.stove.mvp.ios.vn.notification", notificationServicePlistPath);
                }
                else
                {
                    notificationServiceTarget = PBXProjectExtensions.AddAppExtension(pbxProject, targetGuid, "NotificationServiceExtension", PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS) + ".notification", notificationServicePlistPath);
                }
            }

            var buildPhaseID = pbxProject.AddSourcesBuildPhase(notificationServiceTarget);
            pbxProject.AddFileToBuildSection(notificationServiceTarget, buildPhaseID, pbxProject.AddFile(pathToNotificationService + "NotificationService.m", "NotificationService/NotificationService.m", PBXSourceTree.Source));

            pbxProject.SetBuildProperty(notificationServiceTarget, "ARCHS", "$(ARCHS_STANDARD)");
            pbxProject.SetBuildProperty(notificationServiceTarget, "DEVELOPMENT_TEAM", "YOUR_TEAM_ID");
            pbxProject.SetBuildProperty(notificationServiceTarget, "IPHONEOS_DEPLOYMENT_TARGET", MinimumIOSDeploymentTarget);

            if (StoveSettings.EnableGUID)
            {
                if (StoveSettings.EnableVTCO)
                {
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_UUID");
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_NAME");
                }
                else
                {
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_UUID");
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_NAME");
                }
            }
            else
            {
                if (StoveSettings.EnableVTCO)
                {
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_UUID");
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_NAME");
                }
                else
                {
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_UUID");
                    pbxProject.SetBuildProperty(notificationServiceTarget, "PROVISIONING_PROFILE_SPECIFIER", "YOUR_NOTIFICATION_PROVISIONING_PROFILE_NAME");
                }
            }

            pbxProject.SetBuildProperty(notificationServiceTarget, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(notificationServiceTarget, "SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD", "NO");
            pbxProject.SetBuildProperty(notificationServiceTarget, "CLANG_ENABLE_MODULES", "YES");

            pbxProject.AddBuildProperty(notificationServiceTarget, "LIBRARY_SEARCH_PATHS", "$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LIBRARY_SEARCH_PATHS", "$(SDKROOT)/usr/lib/swift");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LIBRARY_SEARCH_PATHS", "$(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME)");
            
            pbxProject.SetBuildProperty(notificationServiceTarget, "LD_RUNPATH_SEARCH_PATHS", "/usr/lib/swift");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LD_RUNPATH_SEARCH_PATHS", "$(inherited)");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks");
            pbxProject.AddBuildProperty(notificationServiceTarget, "LD_RUNPATH_SEARCH_PATHS", "@loader_path/Frameworks");
        }

        // Apply settings
        File.WriteAllText(projectPath, pbxProject.WriteToString());

        if (buildType == "adhoc")
        {
            ProjectCapabilityManager projectCapabilityManager = new ProjectCapabilityManager(projectPath, "NotificationService.entitlements", "NotificationServiceExtension");

            if (StoveSettings.EnableGUID)
            {
                if (StoveSettings.EnableVTCO)
                {
                    projectCapabilityManager.AddAppGroups(new string[] { "group.com.stove.mvp.ios.guid.vn" });
                }
                else
                {
                    projectCapabilityManager.AddAppGroups(new string[] { "group.com.stove.mvp.ios.guid" });
                }
            }
            else
            {
                if (StoveSettings.EnableVTCO)
                {
                    projectCapabilityManager.AddAppGroups(new string[] { "group.com.stove.mvp.ios.vn" });
                }
                else
                {
                    projectCapabilityManager.AddAppGroups(new string[] { "group.com.stove.mvp.ios" });
                }
            }

            projectCapabilityManager.AddKeychainSharing(new string[] { "$(AppIdentifierPrefix)com.stove.globaldata" });
            projectCapabilityManager.WriteToFile();
        }

        string text = System.IO.File.ReadAllText(projectPath);
        //text = text.Replace("DEVELOPMENT_TEAM = \"\"", "DEVELOPMENT_TEAM = \"YOUR_TEAM_ID\"");
        text = text.Replace("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\"", "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"YOUR_CODE_SIGN_IDENTITY\"");
        text = text.Replace("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iOS Developer\"", "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"YOUR_CODE_SIGN_IDENTITY\"");
        text = text.Replace("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"Apple Development\"", "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"YOUR_CODE_SIGN_IDENTITY\"");
        text = RaiseIOSDeploymentTargets(text);

        System.IO.File.WriteAllText(projectPath, text);

        // Samlpe of editing Info.plist
        var plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
        var plist = new PlistDocument();
        plist.ReadFromFile(plistPath);

        ConfigureSceneManifestForSample(plist, Application.unityVersion);

        plist.root.SetString("NSCameraUsageDescription", "");
        plist.root.SetString("NSPhotoLibraryUsageDescription", "");
        plist.root.SetString("NSPhotoLibraryAddUsageDescription", "");
        plist.root.SetString("NSMicrophoneUsageDescription", "");
        plist.root.SetString("NSUserTrackingUsageDescription", "");

        var allowsDict = plist.root.CreateDict("NSAppTransportSecurity");
        allowsDict.SetBoolean("NSAllowsArbitraryLoads", true);

        // Add string setting
        plist.root.SetString("StoveEnvironment", StoveSettings.Zone);
        plist.root.SetBoolean("StoveEnableGUID", StoveSettings.EnableGUID);

        var languages = plist.root.CreateArray("CFBundleLocalizations");
        languages.AddString("ar");
        languages.AddString("cs");
        languages.AddString("de");
        languages.AddString("en");
        languages.AddString("es");
        languages.AddString("fr");
        languages.AddString("id");
        languages.AddString("it");
        languages.AddString("ja");
        languages.AddString("ko");
        languages.AddString("ms");
        languages.AddString("nl");
        languages.AddString("pl");
        languages.AddString("pt");
        languages.AddString("ru");
        languages.AddString("th");
        languages.AddString("tr");
        languages.AddString("zh-Hans");
        languages.AddString("zh-Hant");
        languages.AddString("vi");

        if (StoveSettings.FacebookEnabled)
        {
            plist.root.SetString("FacebookAppID", StoveSettings.FacebookAppId);
            plist.root.SetString("FacebookClientToken", StoveSettings.FacebookClientToken);
        }

        if (StoveSettings.GoogleEnabled)
        {
            plist.root.SetString("GoogleClientID", StoveSettings.GoogleIosClientId);
        }

        if (StoveSettings.NaverEnabled)
        {
            plist.root.SetString("NidClientID", StoveSettings.NaverClientId);
            plist.root.SetString("NidAppName", StoveSettings.NaverClientName);
            plist.root.SetString("NidClientSecret", StoveSettings.NaverClientSecret);
            plist.root.SetString("NidUrlScheme", StoveSettings.NaverUrlScheme);
        }

        if (StoveSettings.SanctionType)
        {
            plist.root.SetInteger("StoveSanctionType", 1);
        }

        // scheme whitelist
        var queriesSchemes = plist.root.CreateArray("LSApplicationQueriesSchemes");
        queriesSchemes.AddString("mstove");

        // Add URL Scheme
        var array = plist.root.CreateArray("CFBundleURLTypes");
        var urlDict = array.AddDict();
        var urlInnerArray = urlDict.CreateArray("CFBundleURLSchemes");

        if (StoveSettings.EnableGUID)
        {
            if (StoveSettings.EnableVTCO)
            {
                urlInnerArray.AddString("com.stove.mvp.ios.guid.vn");
            }
            else
            {   
                urlInnerArray.AddString("com.stove.mvp.ios.guid");
            }
        }
        else
        {
            if (StoveSettings.EnableVTCO)
            {
                urlInnerArray.AddString("com.stove.mvp.ios.vn");
            }
            else
            {
                urlInnerArray.AddString("com.stove.mvp.ios");
            }
        }

        if (StoveSettings.FacebookEnabled)
        {
            urlInnerArray.AddString("fb" + StoveSettings.FacebookAppId);
            queriesSchemes.AddString("fbapi");
            queriesSchemes.AddString("fb-messenger-share-api");
            queriesSchemes.AddString("fbauth2");
            queriesSchemes.AddString("fbshareextension");
        }

        if (StoveSettings.GoogleEnabled)
        {
            urlInnerArray.AddString(StoveSettings.GoogleIosUrlScheme);
        }

        if (StoveSettings.NaverEnabled)
        {
            urlInnerArray.AddString(StoveSettings.NaverUrlScheme);
            queriesSchemes.AddString("naversearchapp");
            queriesSchemes.AddString("naversearchthirdlogin");
        }

        if (StoveSettings.LineEnabled)
        {
            plist.root.SetString("LINE_CHANNEL_ID", StoveSettings.LineChannelId);
            urlInnerArray.AddString("line3rdp.$(PRODUCT_BUNDLE_IDENTIFIER)");
            queriesSchemes.AddString("lineauth2");
        }

        // Apply editing settings to Info.plist
        plist.WriteToFile(plistPath);

        foreach (string podFilePath in PodFilePaths)
        {
            if (StoveSettings.EnableGUID)
            {
                CopyAndReplaceFile(podFilePath + "_GUID", Path.Combine(pathToBuiltProject, Path.GetFileName(PodFilePath)));
            }
            else
            {
                CopyAndReplaceFile(podFilePath, Path.Combine(pathToBuiltProject, Path.GetFileName(PodFilePath)));
            }
        }

        // StartPodsProcess(pathToBuiltProject);

        if (StoveSettings.EnableGUID)
        {
            CopyAndReplaceFile(NotificationServiceEntitlementsFilePathForGUID, Path.Combine(pathToBuiltProject, Path.GetFileName(NotificationServiceEntitlementsFilePathForGUID)));
            CopyAndReplaceFile(SDKEntitlementsFilePathForGUID, Path.Combine(pathToBuiltProject, Path.GetFileName(SDKEntitlementsFilePathForGUID)));
        }
        else
        {
            CopyAndReplaceFile(NotificationServiceEntitlementsFilePath, Path.Combine(pathToBuiltProject, Path.GetFileName(NotificationServiceEntitlementsFilePath)));
            CopyAndReplaceFile(SDKEntitlementsFilePath, Path.Combine(pathToBuiltProject, Path.GetFileName(SDKEntitlementsFilePath)));
        }
    }

    // Xcode 27 이상은 IPHONEOS_DEPLOYMENT_TARGET 15.0 미만을 빌드 에러로 처리한다.
    const string MinimumIOSDeploymentTarget = "15.0";

    internal static string RaiseIOSDeploymentTargets(string pbxprojText)
    {
        var minimum = double.Parse(MinimumIOSDeploymentTarget, CultureInfo.InvariantCulture);
        return Regex.Replace(
            pbxprojText,
            @"IPHONEOS_DEPLOYMENT_TARGET = ""?(?<version>\d+(\.\d+)*)""?;",
            match =>
            {
                var version = match.Groups["version"].Value;
                var parts = version.Split('.');
                var majorMinor = parts.Length > 1 ? parts[0] + "." + parts[1] : parts[0];
                double value;
                if (!double.TryParse(majorMinor, NumberStyles.Float, CultureInfo.InvariantCulture, out value) ||
                    value >= minimum)
                    return match.Value;

                return "IPHONEOS_DEPLOYMENT_TARGET = " + MinimumIOSDeploymentTarget + ";";
            });
    }

    internal static bool UsesUnityNativeSceneLifecycle(string unityVersion)
    {
        var match = Regex.Match(
            unityVersion ?? string.Empty,
            @"^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?<stream>[abcfp])(?<build>\d+)");
        if (!match.Success)
        {
            Debug.LogWarning(
                "[STOVE][Unity] Unable to parse Unity version '" + unityVersion +
                "'. Applying the pre-2022.3.72f1 sample path.");
            return false;
        }

        var major = int.Parse(match.Groups["major"].Value);
        var minor = int.Parse(match.Groups["minor"].Value);
        var patch = int.Parse(match.Groups["patch"].Value);
        var stream = match.Groups["stream"].Value[0];
        var build = int.Parse(match.Groups["build"].Value);

        if (major != 2022)
            return major > 2022;
        if (minor != 3)
            return minor > 3;
        if (patch != 72)
            return patch > 72;

        var streamOrder = GetUnityReleaseStreamOrder(stream);
        var finalStreamOrder = GetUnityReleaseStreamOrder('f');
        return streamOrder > finalStreamOrder ||
               (streamOrder == finalStreamOrder && build >= 1);
    }

    private static int GetUnityReleaseStreamOrder(char stream)
    {
        switch (stream)
        {
            case 'a':
                return 0;
            case 'b':
                return 1;
            case 'c':
                return 2;
            case 'f':
                return 3;
            case 'p':
                return 4;
            default:
                return -1;
        }
    }

    private static void ConfigureSceneDelegateForSample(
        PBXProject pbxProject,
        string frameworkTargetGuid,
        string pathToBuiltProject,
        string unityVersion)
    {
        if (UsesUnityNativeSceneLifecycle(unityVersion))
        {
            Debug.Log(
                "[STOVE][Unity] " + unityVersion +
                " uses Unity native Scene lifecycle. " +
                "Stove URL callbacks are handled by StoveSDKAppController.");
            return;
        }

        var exportDirectory = Path.Combine(
            pathToBuiltProject,
            "Libraries/Stove/Sample/SceneDelegate");
        Directory.CreateDirectory(exportDirectory);

        var headerPath = Path.Combine(exportDirectory, "StoveUnitySceneDelegate.h");
        var implementationPath = Path.Combine(exportDirectory, "StoveUnitySceneDelegate.mm");
        CopyAndReplaceFile(
            Path.Combine(SceneDelegateTemplatesPath, "StoveUnitySceneDelegate.h.txt"),
            headerPath);
        CopyAndReplaceFile(
            Path.Combine(SceneDelegateTemplatesPath, "StoveUnitySceneDelegate.mm.txt"),
            implementationPath);

        const string projectDirectory = "Libraries/Stove/Sample/SceneDelegate";
        AddFileReferenceIfMissing(
            pbxProject,
            headerPath,
            projectDirectory + "/StoveUnitySceneDelegate.h");
        var implementationGuid = AddFileReferenceIfMissing(
            pbxProject,
            implementationPath,
            projectDirectory + "/StoveUnitySceneDelegate.mm");
        pbxProject.AddFileToBuild(frameworkTargetGuid, implementationGuid);

        Debug.Log(
            "[STOVE][Unity] " + unityVersion +
            " uses the sample SceneDelegate compatibility path.");
    }

    private static string AddFileReferenceIfMissing(
        PBXProject pbxProject,
        string sourcePath,
        string projectPath)
    {
        var fileGuid = pbxProject.FindFileGuidByProjectPath(projectPath);
        if (string.IsNullOrEmpty(fileGuid))
            fileGuid = pbxProject.AddFile(sourcePath, projectPath, PBXSourceTree.Source);
        return fileGuid;
    }

    private static void ConfigureSceneManifestForSample(
        PlistDocument plist,
        string unityVersion)
    {
        if (UsesUnityNativeSceneLifecycle(unityVersion))
            return;

        var manifest = GetOrCreateDict(plist.root, "UIApplicationSceneManifest");
        manifest.SetBoolean("UIApplicationSupportsMultipleScenes", false);

        var configurations = GetOrCreateDict(manifest, "UISceneConfigurations");
        var applicationRole = GetOrCreateArray(
            configurations,
            "UIWindowSceneSessionRoleApplication");
        var defaultConfiguration = FindSceneConfiguration(
            applicationRole,
            "Default Configuration");

        if (defaultConfiguration == null)
            defaultConfiguration = applicationRole.AddDict();

        defaultConfiguration.SetString(
            "UISceneConfigurationName",
            "Default Configuration");
        defaultConfiguration.SetString(
            "UISceneDelegateClassName",
            "StoveUnitySceneDelegate");
    }

    private static PlistElementDict FindSceneConfiguration(
        PlistElementArray configurations,
        string configurationName)
    {
        foreach (var element in configurations.values)
        {
            var configuration = element as PlistElementDict;
            if (configuration == null)
                continue;

            PlistElement nameElement;
            if (configuration.values.TryGetValue(
                    "UISceneConfigurationName",
                    out nameElement) &&
                nameElement.AsString() == configurationName)
            {
                return configuration;
            }
        }

        return null;
    }

    private static PlistElementDict GetOrCreateDict(
        PlistElementDict parent,
        string key)
    {
        PlistElement element;
        if (parent.values.TryGetValue(key, out element))
        {
            var dictionary = element as PlistElementDict;
            if (dictionary != null)
                return dictionary;
        }

        return parent.CreateDict(key);
    }

    private static PlistElementArray GetOrCreateArray(
        PlistElementDict parent,
        string key)
    {
        PlistElement element;
        if (parent.values.TryGetValue(key, out element))
        {
            var array = element as PlistElementArray;
            if (array != null)
                return array;
        }

        return parent.CreateArray(key);
    }

    internal static void CopyAndReplaceFile(string srcPath, string dstPath)
    {
        if (File.Exists(dstPath))
            File.Delete(dstPath);

        File.Copy(srcPath, dstPath);
    }

    //static void StartPodsProcess(string path)
    //{
    //    var proc = new System.Diagnostics.Process();
    //    proc.StartInfo.FileName = Path.Combine(path, OpenPodsFileName);
    //    proc.Start();
    //}

    static string[] PodFilePaths
    {
        get
        {
            return new[] {
                Path.Combine (PodFolderPath, "Podfile_2021_3")
                //Path.Combine (PodFolderPath, "pods.command"),
                //Path.Combine (PodFolderPath, OpenPodsFileName)
            };
        }
    }

    static string PodFilePath
    {
        get
        {
            return Path.Combine(PodFolderPath, "Podfile");
        }
    }

    //static string OpenPodsFileName
    //{
    //    get
    //    {
    //        return "open_pods.command";
    //    }
    //}

    static string PodFolderPath
    {
        get
        {
            return Path.Combine(XCodeFilesFolderPath, "Pod/");
        }
    }

    static string NotificationServicePath
    {
        get
        {
            return Path.Combine(XCodeFilesFolderPath, "NotificationService/");
        }
    }

    static string SceneDelegateTemplatesPath
    {
        get
        {
            return Path.Combine(XCodeFilesFolderPath, "SceneDelegateTemplates/");
        }
    }

    static string ProjectSettingsEntitlementsFilePath
    {
        get
        {
            if (StoveSettings.EnableGUID)
            {
                if (StoveSettings.EnableVTCO)
                {
                    return "${PROJECT_DIR}/StoveSDK_GUID_VN.entitlements";
                }
                else
                {
                    return "${PROJECT_DIR}/StoveSDK_GUID.entitlements";
                }
            }
            else
            {
                if (StoveSettings.EnableVTCO)
                {
                    return "${PROJECT_DIR}/StoveSDK_VN.entitlements";
                }
                else
                {
                    return "${PROJECT_DIR}/StoveSDK.entitlements";
                }
            }
        }
    }

    static string NotificationServiceEntitlementsFilePath
    {
        get
        {
            if (StoveSettings.EnableVTCO)
            {
                return Path.Combine(NotificationServicePath, "NotificationService_VN.entitlements");
            }
            else
            {
                return Path.Combine(NotificationServicePath, "NotificationService.entitlements");
            }
        }
    }

    static string NotificationServiceEntitlementsFilePathForGUID
    {
        get
        {
            if (StoveSettings.EnableVTCO)
            {
                return Path.Combine(NotificationServicePath, "NotificationService_GUID_VN.entitlements");
            }
            else
            {
                return Path.Combine(NotificationServicePath, "NotificationService_GUID.entitlements");
            }
        }
    }

    static string SDKEntitlementsFilePath
    {
        get
        {
            if (StoveSettings.EnableVTCO)
            {
                return Path.Combine(XCodeFilesFolderPath, "StoveSDK_VN.entitlements");
            }
            else
            {
                return Path.Combine(XCodeFilesFolderPath, "StoveSDK.entitlements");
            }
        }
    }

    static string SDKEntitlementsFilePathForGUID
    {
        get
        {
            if (StoveSettings.EnableVTCO)
            {
                return Path.Combine(XCodeFilesFolderPath, "StoveSDK_GUID_VN.entitlements");
            }
            else
            {
                return Path.Combine(XCodeFilesFolderPath, "StoveSDK_GUID.entitlements");
            }
        }
    }

    static string XCodeFilesFolderPath
    {
        get
        {
            return Path.Combine(UnityProjectRootFolder, "Assets/Stove/Sample/Editor/Settings/");
        }
    }

    static string UnityProjectRootFolder
    {
        get
        {
            return ".";
        }
    }
}
