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

namespace Aidlab
{
    internal static class AidlabMacOSPostprocess
    {
        [PostProcessBuild(1000)]
        private static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
        {
            if (target != BuildTarget.StandaloneOSX)
                return;

            string plistPath = Path.Combine(pathToBuiltProject, "Contents", "Info.plist");
            if (!File.Exists(plistPath))
                return;

            var doc = new XmlDocument();
            doc.Load(plistPath);

            XmlNode dict = doc.SelectSingleNode("/plist/dict");
            if (dict == null)
                return;

            EnsureString(dict, "NSBluetoothAlwaysUsageDescription", "Bluetooth access is required to connect to Aidlab devices.");

            doc.Save(plistPath);
        }

        private static void EnsureString(XmlNode dict, string key, string value)
        {
            for (int i = 0; i < dict.ChildNodes.Count; i++)
            {
                XmlNode node = dict.ChildNodes[i];
                if (node.Name != "key" || node.InnerText != key)
                    continue;

                for (int j = i + 1; j < dict.ChildNodes.Count; j++)
                {
                    XmlNode next = dict.ChildNodes[j];
                    if (next.NodeType == XmlNodeType.Element)
                        return;
                }

                return;
            }

            XmlElement keyNode = dict.OwnerDocument.CreateElement("key");
            keyNode.InnerText = key;
            dict.AppendChild(keyNode);

            XmlElement stringNode = dict.OwnerDocument.CreateElement("string");
            stringNode.InnerText = value;
            dict.AppendChild(stringNode);
        }
    }
}
#endif

