using System.Threading.Tasks;
using Xamarin.Forms;
#if __IOS__
using UIKit;
using Xamarin.Forms.Platform.iOS;
#elif __ANDROID__
using Android.Content;
using Android.Net;
using System.IO;
using System.Linq;
#endif

namespace Pixiview.Utils
{
    public class FileStore
    {
#if __IOS__
        public static Task<string> SaveVideoToGalleryAsync(string file)
        {
            var task = new TaskCompletionSource<string>();
            if (UIVideo.IsCompatibleWithSavedPhotosAlbum(file))
            {
                UIVideo.SaveToPhotosAlbum(file, (path, err) =>
                {
                    task.SetResult(err?.ToString());
                });
            }
            return task.Task;
        }
#endif

        public static Task<string> SaveImageToGalleryAsync(ImageSource image)
        {
#if __IOS__
            IImageSourceHandler renderer;
            if (image is UriImageSource)
            {
                renderer = new ImageLoaderSourceHandler();
            }
            else if (image is FileImageSource)
            {
                renderer = new FileImageSourceHandler();
            }
            else
            {
                renderer = new StreamImagesourceHandler();
            }
            var photo = renderer.LoadImageAsync(image).Result;

            var task = new TaskCompletionSource<string>();
            if (photo == null)
            {
                task.SetResult(null);
            }
            else
            {
                photo.SaveToPhotosAlbum((img, error) =>
                {
                    task.SetResult(error?.ToString());
                });
            }
            return task.Task;
#elif __ANDROID__
            Java.IO.File camera;

            var dirs = Droid.MainActivity.Main.GetExternalMediaDirs();
            camera = dirs.FirstOrDefault();
            if (camera == null)
            {
                camera = Droid.MainActivity.Main.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures);
            }
            if (!camera.Exists())
            {
                camera.Mkdirs();
            }
            var original = ((FileImageSource)image).File;
            var filename = Path.GetFileName(original);
            var imgFile = new Java.IO.File(camera, filename).AbsolutePath;
            File.Copy(original, imgFile);

            var uri = Uri.FromFile(new Java.IO.File(imgFile));
            var intent = new Intent(Intent.ActionMediaScannerScanFile);
            intent.SetData(uri);
            Droid.MainActivity.Main.SendBroadcast(intent);

            var task = new TaskCompletionSource<string>();
            task.SetResult(null);
            return task.Task;
#endif
        }
    }
}
