using System;
using Foundation;
using UIKit;
using UserNotifications;
using System.IO;
using System.Diagnostics;

namespace XamarinDemoAppServiceExtension
{
    [Register("NotificationService")]
    public class NotificationService : UNNotificationServiceExtension
    {
        Action<UNNotificationContent> ContentHandler { get; set; }
        UNMutableNotificationContent BestAttemptContent { get; set; }

        protected NotificationService(IntPtr handle) : base(handle)
        {
            // Note: this .ctor should not contain any initialization logic.
        }

        public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
        {
            ContentHandler = contentHandler;
            BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();

            if (BestAttemptContent == null)
            {
                Debug.WriteLine("Push Content is empty");
                return;
            }
            if (!BestAttemptContent.UserInfo.ContainsKey(new NSString("data")))
            {
                Debug.WriteLine("There is no data in push notification");
                return;
            }
            var notificationData = BestAttemptContent.UserInfo.ObjectForKey(new NSString("data")) as NSDictionary;
            if (notificationData == null)
            {
                Debug.WriteLine("There is no content in data in push notification");
                return;
            }
            var urlString = notificationData.ObjectForKey(new NSString("attachment-url")) as NSString;
            if (urlString == null)
            {
                Debug.WriteLine("attachment-url does not exist in push notification");
                return;
            }
            NSUrl fileUrl = NSUrl.FromString(urlString);
            if (fileUrl == null)
            {
                Debug.WriteLine("fileUrl is empty in push notification");
                return;
            }

            NSUrlSessionDownloadTask downloadTask = NSUrlSession.SharedSession.CreateDownloadTask(NSUrlRequest.FromUrl(fileUrl), (location, response, error) =>
            {
                if (location != null && error == null)
                {
                    string tempDir = Path.GetTempPath();
                    string suggestedName = response.SuggestedFilename;
                    if (suggestedName != null)
                    {
                        string fileName = "file://" + tempDir + suggestedName;
                        string tempFileName = fileName.Replace(" ", "_");
                        NSUrl tempUrl = NSUrl.FromString(tempFileName);

                        NSError removeFileError = null;
                        if (NSFileManager.DefaultManager.FileExists(tempUrl.Path) &&
                            NSFileManager.DefaultManager.IsDeletableFile(tempUrl.Path))
                        {
                            NSFileManager.DefaultManager.Remove(tempUrl.Path, out removeFileError);
                        }

                        if (removeFileError != null)
                        {
                            Debug.WriteLine("removeFileError" + removeFileError.DebugDescription);
                            return;
                        }

                        NSError moveFileError = null;
                        NSFileManager.DefaultManager.Move(location, tempUrl, out moveFileError);
                        if (moveFileError != null)
                        {
                            Debug.WriteLine("moveFileError" + moveFileError.DebugDescription);
                            return;
                        }

                        NSError attachmentError = null;
                        UNNotificationAttachment attachment = UNNotificationAttachment.FromIdentifier("ci360content", tempUrl, (NSDictionary)null, out attachmentError);
                        if (attachmentError != null)
                        {
                            Debug.WriteLine("attachmentError" + attachmentError.DebugDescription);
                            return;
                        }

                        BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment };
                    }
                }
                ContentHandler(BestAttemptContent);
            });

            downloadTask.Resume();

        }

        public override void TimeWillExpire()
        {
            // Called just before the extension will be terminated by the system.
            // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.

            ContentHandler(BestAttemptContent);
        }
    }
}

