using System.IO;
using UnityEngine;
using UnityEditor;
#if UNITY_IOS
using UnityEditor.Build.Reporting;
using UnityEditor.iOS.Xcode;
#endif
using UnityEditor.Callbacks;


namespace SuperAwesome.Unity.PostProcess
{
    /// <summary>
    /// Configures iOS build settings (disables Bitcode, enables Clang modules).
    /// Also injects the AdMob GADApplicationIdentifier into Info.plist.
    /// The SuperAwesome SPM dependency is handled by EDM4U via SuperAwesomeDependencies.xml.
    /// </summary>
    public static class DisableBitcode
    {
        [PostProcessBuildAttribute(999)]
        public static void OnPostProcessBuild(BuildTarget buildTarget, string pathToBuildProject)
        {
#if UNITY_IOS
            if (buildTarget != BuildTarget.iOS) return;
            string projectPath = pathToBuildProject + "/Unity-iPhone.xcodeproj/project.pbxproj";
            PBXProject pbxProject = new PBXProject();
            pbxProject.ReadFromFile(projectPath);

            //Disabling Bitcode on all targets
            //Main
            string target = pbxProject.GetUnityMainTargetGuid();
            pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");
            //Unity Tests
            target = pbxProject.TargetGuidByName(PBXProject.GetUnityTestTargetName());
            pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");
            //Unity Framework
            string frameworkTarget = pbxProject.GetUnityFrameworkTargetGuid();
            pbxProject.SetBuildProperty(frameworkTarget, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(frameworkTarget, "CLANG_ENABLE_MODULES", "YES");

            pbxProject.WriteToFile(projectPath);

            // Inject AdMob App ID into Info.plist.
            // Using Google's demo App ID for testing purposes.
            // Replace with your own App ID from https://apps.admob.com before releasing.
            // See: https://developers.google.com/admob/ios/test-ads
            string plistPath = pathToBuildProject + "/Info.plist";
            var plist = new PlistDocument();
            plist.ReadFromFile(plistPath);
            plist.root.SetString("GADApplicationIdentifier", "ca-app-pub-3940256099942544~1458002511");
            plist.WriteToFile(plistPath);
#endif
        }
    }
}
