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

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Google.Android.Material.Snackbar;
using Java.IO;
using System;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace MobileCapture.Sample.Droid
{
    [Activity(Label = "MobileCapture.Sample", Icon = "@mipmap/icon", Theme = "@style/MainTheme",
        MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Platform.Init(this, savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);

            DependencyService.Register<AndroidPdfViewer>();

            HandlePermissions();

            LoadApplication(new App());
        }

        const int REQUEST_CODE = 202;

        /// <summary>
        /// In this sample we export the captured images into a PDF file in a public Pictures directory,
        /// so we need to request permission for WriteExternalStorage. If denied, the OpenPdf action results in error
        /// </summary>
        private void HandlePermissions()
        {
            var requiredPermissions = new string[] { Android.Manifest.Permission.WriteExternalStorage };
            if (ActivityCompat.ShouldShowRequestPermissionRationale(this,
                Android.Manifest.Permission.WriteExternalStorage))
            {
                Android.Views.View activityRootView = FindViewById(Android.Resource.Id.Content);
                Snackbar.Make(activityRootView,
                               Resource.String.permission_rationale,
                               Snackbar.LengthIndefinite)
                        .SetAction(Android.Resource.String.Ok,
                                   new Action<Android.Views.View>(delegate (Android.Views.View obj) {
                                       ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_CODE);
                                   }
                        )
                ).Show();
            }
            else
            {
                ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_CODE);
            }
        }

        public override void OnRequestPermissionsResult(int requestCode,
            string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            if (requestCode == REQUEST_CODE)
            {
                var pdfViewer = DependencyService.Get<IPdfViewer>() as AndroidPdfViewer;
                if ((grantResults.Length == 1) && (grantResults[0] == Permission.Granted))
                {
                    pdfViewer.IsPdfExportAllowed = true;
                }
                else
                {
                    pdfViewer.IsPdfExportAllowed = false;
                }
            }
            Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /// <summary>
    /// This is a platform-dependent implementation of the OpenPdf action. On Android the 'Document.pdf' file is stored
    /// in public Pictures/abbyy_xamarin_sample/ folder and viewed via firing an intent
    /// </summary>
    public class AndroidPdfViewer : IPdfViewer
    {
        public bool IsPdfExportAllowed { get; set; }

        [Obsolete]
        public string PdfPath
        {
            get
            {
                if (!IsPdfExportAllowed)
                {
                    throw new Exception("PDF export is not allowed");
                }
                var dir = new File(
                    Android.OS.Environment.GetExternalStoragePublicDirectory(
                        Android.OS.Environment.DirectoryPictures
                    ), "abbyy_xamarin_sample");
                if (!dir.Exists())
                {
                    if (!dir.Mkdirs())
                    {
                        throw new Exception("Cannot create directory for PDF: " + dir.Path);
                    }
                }
                var file = new File(dir, "Document.pdf");
                return file.Path;
            }
        }

        public void Show(string path)
        {
            var context = Android.App.Application.Context;
            var intent = new Intent(Intent.ActionView);
            var file = new File(path);
            intent.SetDataAndType(FileProvider.GetUriForFile(context, context.PackageName+".provider", file), "application/pdf");
            intent.SetFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.ClearTop | ActivityFlags.NoHistory);
            try
            {
                var chooserIntent = Intent.CreateChooser(intent, "Open File");
                chooserIntent = chooserIntent.SetFlags(ActivityFlags.NewTask);
                context.StartActivity(chooserIntent);
            }
            catch (ActivityNotFoundException)
            {
                Android.Widget.Toast.MakeText(context, "Failed to open PDF", Android.Widget.ToastLength.Long).Show();
            }
        }
    }
}