using Autofac;
using InABox.Core;
using Microsoft.Maui.ApplicationModel;


namespace InABox.Avalonia
{
    
    public static class MobileUtils
    {
        
        public static void Init()
        {
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(CoreUtils.SyncfusionLicense(SyncfusionVersion.v29_x));
        }
        
        private static async Task<bool> Retry(Func<Task<bool>> action, int interval, int retryCount = 3)
        {
            bool flag = false;
            List<Exception> source = new List<Exception>();
            TimeSpan delay = TimeSpan.FromMilliseconds((double)interval);
            for (int index = 0; index < retryCount; ++index)
            {
                try
                {
                    flag = await action();
                    if (flag)
                        return true;
                    Task.Delay(delay).Wait();
                }
                catch (Exception ex)
                {
                    if (source.All<Exception>((Func<Exception, bool>)(x => x.Message != ex.Message)))
                        source.Add(ex);
                    Task.Delay(delay).Wait();
                }
            }
            if (!flag && !source.Any<Exception>())
                return false;
            if (source.Count<Exception>() == 1)
                throw source.First();
            if (source.Count<Exception>() > 1)
                throw new AggregateException((IEnumerable<Exception>)source);
            return flag;
        }
        
        public static async Task<bool> IsPermitted<TPermission>() where TPermission : Permissions.BasePermission, new()
        {
            try
            {
                PermissionStatus status = await Permissions.CheckStatusAsync<TPermission>();
                if (status == PermissionStatus.Granted)
                    return true;
                var request = await Permissions.RequestAsync<TPermission>();
                return request == PermissionStatus.Granted;

            }
            catch (TaskCanceledException ex)
            {
                return false;
            }
        }
        
        // public static async Task<bool> CheckPermissions<TPermission>() where TPermission : Permissions.BasePermission, new()
        // {
        //     var permissionStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
        //     bool request = false;
        //     if (permissionStatus == PermissionStatus.Denied)
        //     {
        //         if (String.Equals(Device.RuntimePlatform, Device.iOS))
        //         {
        //
        //             var title = $"{permission} Permission";
        //             var question = $"To use this plugin the {permission} permission is required. Please go into Settings and turn on {permission} for the app.";
        //             var positive = "Settings";
        //             var negative = "Maybe Later";
        //             var task = Application.Current?.MainPage?.DisplayAlert(title, question, positive, negative);
        //             if (task == null)
        //                 return false;
        //
        //             var result = await task;
        //             if (result)
        //             {
        //                 CrossPermissions.Current.OpenAppSettings();
        //             }
        //
        //             return false;
        //         }
        //
        //         request = true;
        //
        //     }
        //
        //     if (request || permissionStatus != PermissionStatus.Granted)
        //     {
        //         var newStatus = await CrossPermissions.Current.RequestPermissionsAsync(permission);
        //         if (newStatus.ContainsKey(permission) && newStatus[permission] != PermissionStatus.Granted)
        //         {
        //             var title = $"{permission} Permission";
        //             var question = $"To use the plugin the {permission} permission is required.";
        //             var positive = "Settings";
        //             var negative = "Maybe Later";
        //             var task = Application.Current?.MainPage?.DisplayAlert(title, question, positive, negative);
        //             if (task == null)
        //                 return false;
        //
        //             var result = await task;
        //             if (result)
        //             {
        //                 CrossPermissions.Current.OpenAppSettings();
        //             }
        //             return false;
        //         }
        //     }
        //
        //     return true;
        // }


        // public static byte[] ImageSourceToByteArray(ImageSource source)
        // {
        //     StreamImageSource streamImageSource = (StreamImageSource)source;
        //     System.Threading.CancellationToken cancellationToken = System.Threading.CancellationToken.None;
        //     Task<Stream> task = streamImageSource.Stream(cancellationToken);
        //     Stream stream = task.Result;
        //     byte[] bytes = new byte[stream.Length];
        //     stream.Read(bytes, 0, bytes.Length);
        //     return bytes;
        // }
        //
        // public static string ImageSourceToBase64(ImageSource source)
        // {
        //     var bytes = ImageSourceToByteArray(source); 
        //     string s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
        //     return s;
        // }
        
    }
}
