#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;

#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif

namespace Aidlab
{
    internal static class AidlabIOSPostprocess
    {
        [PostProcessBuild(1000)]
        private static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
        {
#if !UNITY_IOS
            return;
#else
            if (target != BuildTarget.iOS)
                return;

            string plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
            if (File.Exists(plistPath))
            {
                var plist = new PlistDocument();
                plist.ReadFromFile(plistPath);
                PlistElementDict root = plist.root;
                root.SetString("NSBluetoothAlwaysUsageDescription", "Bluetooth access is required to connect to Aidlab devices.");
                plist.WriteToFile(plistPath);
            }

            string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
            if (!File.Exists(projPath))
                return;

            var proj = new PBXProject();
            proj.ReadFromFile(projPath);

            string mainTarget = proj.GetUnityMainTargetGuid();
            proj.AddFrameworkToProject(mainTarget, "CoreBluetooth.framework", false);

            string frameworkTarget = proj.GetUnityFrameworkTargetGuid();
            if (!string.IsNullOrEmpty(frameworkTarget))
                proj.AddFrameworkToProject(frameworkTarget, "CoreBluetooth.framework", false);

            proj.WriteToFile(projPath);
#endif
        }
    }
}
#endif

