﻿using UnityEditor;
using UnityEditor.Callbacks;

namespace Yodo1.FanCraft
{
    public class PostprocessBuild
    {
        [PostProcessBuild(9990)]
        public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
        {
            if (buildTarget == BuildTarget.Android)
            {
#if UNITY_ANDROID
                FanCraftSettings settings = SettingsManager.Load();
                if (settings != null && settings.notificationSettingsAndroid.Enable)
                {
                    SDKWindow_Android.GooglePlay(settings);
                }
#endif
            }
            else if (buildTarget == BuildTarget.iOS)
            {
#if UNITY_IOS || UNITY_IPHONE
                FanCraftSettings settings = SettingsManager.Load();
                if (settings != null && settings.notificationSettingsIOS.Enable)
                {
                    AddCapability(pathToBuiltProject, settings);
                    AddCycleMethods(pathToBuiltProject);
                }
#endif
            }
        }

        #region iOS Remote Push Notification

#if UNITY_IOS || UNITY_IPHONE
        private static void AddCapability(string pathToBuiltProject, FanCraftSettings settings)
        {
            //This is the default path to the default pbxproj file. Yours might be different
            string projectPath = "/Unity-iPhone.xcodeproj/project.pbxproj";
            //Default target name. Yours might be different
            string targetName = "Unity-iPhone";
            string entitlementsFileName = "Unity-iPhone.entitlements";

            var entitlements =
 new UnityEditor.iOS.Xcode.ProjectCapabilityManager(pathToBuiltProject + projectPath, entitlementsFileName, targetName);
            entitlements.AddPushNotifications(settings.notificationSettingsIOS.development);
            entitlements.AddBackgroundModes(UnityEditor.iOS.Xcode.BackgroundModesOptions.RemoteNotifications);
            //Apply
            entitlements.WriteToFile();
        }

        private static void AddCycleMethods(string pathToBuiltProject)
        {
            XCodeClass UnityAppController = new XCodeClass(pathToBuiltProject + "/Classes/UnityAppController.mm");

            string importFanCraftPushNotificationCenter = "#import \"FanCraftPushNotificationCenter.h\"";
            if (!UnityAppController.IsHaveText(importFanCraftPushNotificationCenter))
            {
                UnityAppController.WriteBelow("#import \"UnityAppController.h\"", importFanCraftPushNotificationCenter);
            }

            string UNITY_USES_REMOTE_NOTIFICATIONS = "#if UNITY_USES_REMOTE_NOTIFICATIONS";

            string YODO1_USES_REMOTE_NOTIFICATIONS = "#pragma mark - YODO1_USES_REMOTE_NOTIFICATIONS";
            if (!UnityAppController.IsHaveText(YODO1_USES_REMOTE_NOTIFICATIONS))
            {
                string pargmaMark = YODO1_USES_REMOTE_NOTIFICATIONS + "\n\n" + UNITY_USES_REMOTE_NOTIFICATIONS;
                UnityAppController.Replace(UNITY_USES_REMOTE_NOTIFICATIONS, pargmaMark);
            }

            string postNotificationWithToken =
 "[self sendNotificationWithArg:kYodo1DidRegisterForRemoteNotificationsWithDeviceToken arg:deviceToken];";
            if (!UnityAppController.IsHaveText(postNotificationWithToken))
            {
                string didRegisterForRemoteNotificationsWithDeviceToken =
                    "- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken\n{\n" +
                    "\t" + postNotificationWithToken + "\n" +
                    "}\n\n" +
                    UNITY_USES_REMOTE_NOTIFICATIONS;
                UnityAppController.Replace(UNITY_USES_REMOTE_NOTIFICATIONS, didRegisterForRemoteNotificationsWithDeviceToken);
            }

            string postNotificationWithError =
 "[self sendNotificationWithArg:kYodo1DidFailToRegisterForRemoteNotificationsWithError arg:error];";
            if (!UnityAppController.IsHaveText(postNotificationWithError))
            {
                string didRegisterForRemoteNotificationsWithError =
                    "- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\n{\n" +
                    "\t" + postNotificationWithError + "\n" +
                    "}\n\n" +
                    UNITY_USES_REMOTE_NOTIFICATIONS;
                UnityAppController.Replace(UNITY_USES_REMOTE_NOTIFICATIONS, didRegisterForRemoteNotificationsWithError);
            }

            string postNotificationDidReceiveRemoteNotification =
 "[self sendNotificationWithArg:kYodo1DidReceiveRemoteNotification arg:userInfo];";
            if (!UnityAppController.IsHaveText(postNotificationDidReceiveRemoteNotification))
            {
                string didReceiveRemoteNotification =
                    "- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler\n{\n" +
                    "\t" + postNotificationDidReceiveRemoteNotification + "\n" +
                    "\tif (handler) {  handler(UIBackgroundFetchResultNoData); } \n" +
                    "}\n\n" +
                    UNITY_USES_REMOTE_NOTIFICATIONS;
                UnityAppController.Replace(UNITY_USES_REMOTE_NOTIFICATIONS, didReceiveRemoteNotification);
            }

            string sendNotificationMethod = "- (void)sendNotificationWithArg:(NSString*)name arg:(id)arg {";
            if (!UnityAppController.IsHaveText(sendNotificationMethod))
            {
                string sendNotificationMethodText =
                    "- (void)sendNotificationWithArg:(NSString*)name arg:(id)arg { \n" +
                    "\t[[NSNotificationCenter defaultCenter] postNotificationName: name object:self userInfo:arg];\n" +
                    "}\n\n" +
                    UNITY_USES_REMOTE_NOTIFICATIONS;
                UnityAppController.Replace(UNITY_USES_REMOTE_NOTIFICATIONS, sendNotificationMethodText);
            }

        }

#endif

        #endregion
    }
}