// ABBYY® Mobile Capture © 2019 ABBYY Production LLC.
// ABBYY is a registered trademark or a trademark of ABBYY Software Ltd.

using Foundation;
using System;
using UIKit;
using Xamarin.Forms;
using System.IO;

namespace MobileCapture.Sample.iOS
{
    [Register("AppDelegate")]
    public class AppDelegate : Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            Xamarin.Forms.Forms.Init();
            // Platform-dependent Mobile Capture SDK implementations registration
            Forms.iOS.DependencyManager.Register();
            // Sample pdf viewer registration
            DependencyService.Register<IOSPdfViewer>();

            LoadApplication(new App());

            return base.FinishedLaunching(uiApplication, launchOptions);
        }
    }

    /// <summary>
    /// This is a platform-dependent implementation of pdf viewer.
    /// Designed to demonstrate a document export via `ExportPdfAsync` function.
    /// </summary>
    public class IOSPdfViewer : NSObject, IPdfViewer
    {
        /// <summary>
        /// Sample document will be saved in a documents folder.
        /// </summary>
        public string PdfPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Document.pdf");

        public void Show(string path)
        {
            Device.BeginInvokeOnMainThread(delegate
            {
                var pdfViewController = UIDocumentInteractionController.FromUrl(new NSUrl(path, false));
                pdfViewController.WeakDelegate = this;
                pdfViewController.PresentPreview(true);
            });
        }

        /// <summary>
        /// UIDocumentInteractionControllerDelegate implementation
        /// </summary>
        /// <param name="_">The document interaction controller requesting the parent view controller.</param>
        /// <returns>The view controller to use when presenting the document preview.</returns>
        [Export("documentInteractionControllerViewControllerForPreview:")]
        UIViewController documentInteractionControllerViewControllerForPreview(UIDocumentInteractionController _)
        {
            var topViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (topViewController.PresentedViewController != null)
            {
                topViewController = topViewController.PresentedViewController;
            }
            return topViewController;
        }
    }
}
