using System.Threading.Tasks;
using Pixiview.iOS.Services;
using Pixiview.Utils;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: Dependency(typeof(FileStore))]
namespace Pixiview.iOS.Services
{
    public class FileStore : IFileStore
    {

        public Task<string> SaveImageToGalleryAsync(ImageSource image)
        {
            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;
        }
    }
}
