using Foundation;
using MobileCoreServices;
using UIKit;

namespace Pixiview.iOS.OpenExtension
{
    [Register("OpenExtensionHandler")]
    public class OpenExtensionHandler : NSExtensionRequestHandling
    {

        public override void BeginRequestWithExtensionContext(NSExtensionContext context)
        {
            bool urlFound = false;

            foreach (var item in context.InputItems)
            {
                foreach (var provider in item.Attachments)
                {
                    if (provider.HasItemConformingTo(UTType.URL))
                    {
                        provider.LoadItem(UTType.URL, null, (obj, error) =>
                        {
                            var url = obj as NSUrl;
                            if (url != null)
                            {
                                var uri = NSUrl.FromString($"pixiview://open{url.Path}");
                                System.Diagnostics.Debug.WriteLine($"open url: {uri}");
                                BeginInvokeOnMainThread(() => UIApplication.SharedApplication.OpenUrl(uri));
                            }
                        });

                        urlFound = true;
                        break;
                    }
                }

                if (urlFound)
                {
                    break;
                }
            }

            context.CompleteRequest(new NSExtensionItem[0], null);
        }
    }
}
