using System.Text.RegularExpressions;
using Android.Content;
using Android.Runtime;
using InABox.Core;
using Net = Android.Net;

namespace InABox.Avalonia.Platform.Android
{
    public class Android_AppVersion : IAppVersion
    {
        string _packageName = "";
        string _versionName = "";

        public Logger? Logger { get; set; }

        public Android_AppVersion() : base()
        {
            try
            {
                _packageName = Application.Context.PackageName;
                _versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, 0).VersionName;
            }
            catch
            {

            }
        }

        /// <inheritdoc />
        public string InstalledVersionNumber() => _versionName;

        /// <inheritdoc />
        public async Task<bool> IsUsingLatestVersion()
        {
            try
            {
                var info = await GetLatestVersion(false);
                return String.IsNullOrWhiteSpace(info.Version) 
                       || (Version.Parse(info.Version).CompareTo(Version.Parse(_versionName)) <= 0);
            }
            catch (Exception e)
            {
                Logger?.Error($"Error in IsUsingLatestVersion(): {e.Message}\n{e.StackTrace}");
            }

            return true;
        }
        
        private static AppInfo _info;
        
        public async Task<AppInfo> GetLatestVersion(bool force)
        {
            
            if (force)
                _info = null;
            
            if (_info != null)
                return _info;
            
            _info = new AppInfo();
            
            // https://play.google.com/store/apps/details?id=comal.timesheets.Android&hl=en
            var url = $"https://play.google.com/store/apps/details?id={_packageName}&hl=en";
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    using (var handler = new HttpClientHandler())
                    {

                        handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
                        {
                            //bypass
                            return true;
                        };

                        using (var client = new HttpClient(handler))
                        {
                            try
                            {
                                using (var responseMsg = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                                {
                                    if (!responseMsg.IsSuccessStatusCode)
                                    {
                                        throw new LatestVersionException($"Error connecting to the Play Store. Url={url}.");
                                    }

                                    try
                                    {
                                        var content = responseMsg.Content == null ? null : await responseMsg.Content.ReadAsStringAsync();

                                        var versionMatch = Regex.Match(content, "\\[\\[\\[\"(\\d+\\.\\d+\\.\\d+)").Groups[1];                                        

                                        if (versionMatch.Success)
                                        {
                                            _info.Version = versionMatch.Value.Trim();
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        throw new LatestVersionException($"Error parsing content from the Play Store. Url={url}.", e);
                                    }
                                }
                            }
                            catch (Exception ex1)
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.Error($"Error in GetLatestVersion(): {ex.Message}\n{ex.StackTrace}");
            }

            return _info;
        }
        
        public Task OpenAppInStore()
        {
            try
            {
                try
                {
                    var intent = new Intent(Intent.ActionView, Net.Uri.Parse($"market://details?id={_packageName}"));
                    intent.SetPackage("com.android.vending");
                    intent.SetFlags(ActivityFlags.NewTask);
                    Application.Context.StartActivity(intent);
                }
                catch (ActivityNotFoundException)
                {
                    var intent = new Intent(Intent.ActionView, Net.Uri.Parse($"https://play.google.com/store/apps/details?id={_packageName}"));
                    Application.Context.StartActivity(intent);
                }
            }
            catch (Exception e)
            {
                Logger?.Error($"Error in OpenAppInStore(): {e.Message}\n{e.StackTrace}");
            }

            return Task.FromResult(true);
        }


    }
}
