using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;
using Com.SAS.CI360;
using UserNotifications;
//using ObjCRuntime;
using WindowsAzure.Messaging;
using System.Diagnostics;
//using Xamarin.Essentials;
//using Xamarin.Forms;
using XamarinDemoApp.Services;

namespace XamarinDemoApp.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate 
    {

        private SBNotificationHub Hub { get; set; }
        //private UserNotificationCenterDelegate userNotificationDelegate;
        private XamarinMobileMessagingDelegate messagingDelegate;
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            SASLogger.SetLevel(SASLoggerLevel.All);

            RegisterForRemoteNotifications();

            messagingDelegate = new XamarinMobileMessagingDelegate();
            SASCollector.SetMobileMessagingDelegate2(messagingDelegate);

            return base.FinishedLaunching(app, options);
        }

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        { 
            Hub = new SBNotificationHub(Constants.ConnectionString, Constants.NotificationHubName);

            Hub.UnregisterAll(deviceToken, (error) => {
                if (error != null)
                {
                    Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
                    return;
                }

                NSSet tags = null; // create tags if you want
                Hub.RegisterNative(deviceToken, tags, (errorCallback) => {
                    if (errorCallback != null)
                        Debug.WriteLine("RegisterNative error: " + errorCallback.ToString());
                });
            });


            SASCollector.RegisterForMobileMessages(deviceToken, () =>
            {
                Debug.WriteLine("Registration successful");
            }, () =>
            {
                Debug.WriteLine("Registration failed");
            });
        }

        // This is called when mobile message is received
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) 
        {
                if (!SASCollector.HandleMobileMessage(userInfo, UIApplication.SharedApplication))
                {
                    Console.WriteLine("Handle non-SASCollector message");
                }     
            completionHandler(UIBackgroundFetchResult.NoData);
        }


        // This is called when push notification is received
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
                if (!SASCollector.HandleMobileMessage(userInfo, application))
                {
                    Console.WriteLine("Handle non-SASCollector message");
                }
        }

        

        //private void initializeSDK()
        //{
        //    SASCollector.TagServer = "https://eventsingest-dev.cidev.sas.us/t/mobile";
        //    SASCollector.TenantId = "5f301a8a070001019cc023d7";
        //    SASCollector.AppId = "XamarinDemoApp";
        //    SASCollector.InitializeCollection();

        //    messagingDelegate = new XamarinMobileMessagingDelegate();
        //    SASCollector.SetMobileMessagingDelegate2(messagingDelegate);
        //}


        private void RegisterForRemoteNotifications()
        {
            // register for remote notifications based on system version
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                UNUserNotificationCenter.Current.RequestAuthorization(
                    UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                    (granted, error) =>
                    {
                        if (granted)
                            InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                    });
            }
            else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                new NSSet());

                UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
            }
        }
    }

    public class XamarinMobileMessagingDelegate : SASMobileMessagingDelegate2
    {
        public override void ActionWithLink(string link, SASMobileMessageType type)
        {
            Debug.WriteLine("User clicked link: " + link);
            Boolean isPushNotification = type == SASMobileMessageType.PushNotification;
            MobileMessageHandler.OnMsgLinkClicked(link, isPushNotification);
        }

        public override void MessageDismissed()
        {
            Debug.WriteLine("User dismissed message");
            MobileMessageHandler.OnMsgDismissed();
        }
    }


    /*public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
    {
        public UserNotificationCenterDelegate()
        {
        }

        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            base.WillPresentNotification(center, notification, completionHandler);

            //if (!SASCollector.HandleMobileMessage(, UIApplication.SharedApplication))
            //{
            //    Console.WriteLine("Handle non-SASCollector message");
            //}
            completionHandler(UNNotificationPresentationOptions.Alert);
        }

        public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
        {
            var userInfo = response.Notification.Request.Content.UserInfo;
            if (!SASCollector.HandleMobileMessage(userInfo, UIApplication.SharedApplication))
            {
                Console.WriteLine("Handle non-SASCollector message");
            }
            completionHandler();
        }

    } */

}

